arjun sharma
arjun sharma

Reputation: 31

float.TryParse() rounded the value in C#

while trying to parse variable to float with following parameter float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue),

the value=6666.77777 is rounded of to 6666.778.

can anyone help, i don't want my value to be rounded.

Upvotes: 1

Views: 9469

Answers (4)

neeKo
neeKo

Reputation: 4280

That is because value 666.77777 cannot be represented in the binary form floating point numbers use - the actual number contains more binary digits than the floating point has room for. The resulting number is the closest approximation.

Rounding is used when the exact result of a floating-point operation (or a conversion to floating-point format) would need more digits than there are digits in the significand. IEEE 754 requires correct rounding: that is, the rounded result is as if infinitely precise arithmetic was used to compute the value and then rounded (although in implementation only three extra bits are needed to ensure this). There are several different rounding schemes (or rounding modes). Historically, truncation was the typical approach. Since the introduction of IEEE 754, the default method (round to nearest, ties to even, sometimes called Banker's Rounding) is more commonly used.

You should consider using double if you need more precision, or decimal if you need even more than that, though they too suffer from precision loss at some point.

Upvotes: 1

Furqan Safdar
Furqan Safdar

Reputation: 16708

Why don't you use Double.TryParse or Decimal.TryParse to support higher precision:

float: Approximately ±1.5 x 10-45 to ±3.4 x 1038 with 7 significant figures

double: Approximately ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 significant figures

decimal: Approximately ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 significant figures

Try this piece of code snippet instead:

double fValue;
double.TryParse("6666.77777", NumberStyles.Double, CultureInfo.InvariantCulture, out fValue);

OR

decimal fValue;
decimal.TryParse("6666.77777", NumberStyles.Decimal, CultureInfo.InvariantCulture, out fValue);

Upvotes: 1

Joey
Joey

Reputation: 354734

float only has around 6 significant digits. Note that digits before the decimal point count too. double has higher precision in that regard (around 16):

PS> [float]::Parse('6666,77777')
6666.778
PS> [double]::Parse('6666,77777')
6666.77777

But as others noted, this is just an approximate value because it cannot be represented exactly in base 2. If you need decimal exactness (e.g. for money values) then use a decimal. For most other things binary floating point (i.e. float and double) should be fine.

Upvotes: 3

Mayank
Mayank

Reputation: 8852

you should use decimal if you need higher precision.

Upvotes: 0

Related Questions