Groups | Blog | Home
all groups > c# > april 2004 >

c# : Numbers being rounded off!


V. Jenks
4/14/2004 9:34:38 PM
I'm having a problem with the Convert.ToSingle and the
O:C formatting rounding off my floating-point numbers.

When I .ToString a float, it rounds the number. It also
rounds it if I use the "C" or "F" format strings (i.e.
num.ToString("C"))

How can I accurately display a float/currency value w/o
it being rounded off?

Thanks!

anonymous NO[at]SPAM discussions.microsoft.com
4/14/2004 10:56:02 PM
That didn't work at all.

Using .ToString("R") turned 10.99 into 11, for example.

I'm also looking at my data, it's definitely 10.99
there....but all I can manage to get out is a rounded
number, even using "R".

-v

[quoted text, click to view]
Michael Giagnocavo [MVP]
4/15/2004 1:16:13 AM
See the docs on System.Globalization.NumberFormatInfo:
r, R - Roundtrip format, which ensures that numbers converted
to strings will have the same value when they are converted back to numbers.

So if you use "R", then you can be sure the number will convert right back
into the number you have. For currency, don't use a float. Use a decimal.

-Michael
MVP

[quoted text, click to view]
Morten Wennevik
4/15/2004 8:25:51 AM
Could you show a small but complete sample code that demonstrates your
error?

Happy coding!
Jon Skeet [C# MVP]
4/15/2004 8:32:50 AM
[quoted text, click to view]

I suspect you'll find that you've got a problem reading your data then.
The float closest to 10.99 certainly wouldn't be displayed as 11 using
the "R" specifier.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button