Forum Moderators: open

Message Too Old, No Replies

Losing Digits after Decimal Point

Data Type / Conversion Question in C#

         

Argblat

8:05 pm on Mar 27, 2006 (gmt 0)

10+ Year Member



I don't know if it's in the Data Type I'm choosing, or the conversion to a string, but what gives with the following code

Code:
float Pi = 22/7;
lblMsg.Text = Pi.ToString();

Output: 3

-Mike

Easy_Coder

2:54 am on Mar 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Good question! You can try passing a format provider into the .ToString() constructor sorta like this...

using System; 
using System.Globalization;
class FloatToString
{
static void Main(string[] args)
{
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
float Pi = 22/7;
Console.WriteLine(Pi.ToString("n", nfi)); // pass number format
// returns 3.00
}
}

The other format flags are:
c - currency
d - decimal
e - exponential
f - fixed point
g - general
n - number
r - roundtrip
x - hexidecimal

Take a look at the NumberFormatInfo Class

emsaw

3:52 pm on Mar 28, 2006 (gmt 0)

10+ Year Member



Argblat,

The compiler probably needs a bigger hint...

try 22.0 / 7.0
and see if that gets you your floating point.

Mark

duckhunter

4:16 am on Mar 30, 2006 (gmt 0)

10+ Year Member



Try using a Double instead of Float.

This VB code returned: 3.14285714285714

Dim Pi As Double
Pi = 22 / 7
Response.Write(Pi.ToString)

Alternatively, does the C++ float offer optional parameters at declaration? Since 22/7 has decimals, if 3 is being returned then it's the variable that's truncating it.

Bluesplinter

3:21 pm on Apr 1, 2006 (gmt 0)

10+ Year Member



Just nudge the compiler a bit when assigning literals to a float, by changing this line in your original code to read:

float Pi = 22f / 7f;

Produces "3.142857" on my machine.

Argblat

6:33 pm on Apr 3, 2006 (gmt 0)

10+ Year Member



Thank for all the great responses.

emsaw's solution is probably the easiest given my simplified problem, but all of your suggestions will certainly be useful to anyone who needs to weigh a couple of options, so thank you all again!

-Mike