Reputation: 2745
i want to set 20770897 to C# float type but this is changed to 20770896 ! why?
for example:
float test = 20770897;
value automatic changed to 20770896 ? help please. i am getting id from web service . these is return a float value but it is not true value from web service method!
Upvotes: 1
Views: 2345
Reputation: 388
It's a rounding error, these are common in very large or very small values with 32-bit floating types. Use a more precise type like double
if you need floating point support. If you to not explicitly need floating point support I recommend using an int
, long
, uint
, or ulong
to store the value (which appears to be an integer value).
http://en.wikipedia.org/wiki/Round-off_error
Upvotes: 2
Reputation: 10708
The issue is one of a rounding error - because of the precise way values are stored under the hood, noninteger types are incapable of string certain values, and will instead be slightly above or below the actual value. This can result in apparent errors when rounding versus truncating, and you should carefully determine which to use - presumably, you code is producing 20770896.99999... and truncating to 20770896 when you print it.
Note that errors become more frequent the higher your value gets. If you need more accuracy, consider turning up to double
or even decimal
types.
Upvotes: 2
Reputation: 38130
The precision of a float
(System.Single
) is only 7 significant digits
Upvotes: 8