简体   繁体   中英

C# Double.ToString() wrong result

I am trying to display a double value using ToString() methode. the value is 1.000000000000113. , using Double.ToString("F16") result 1.0000000000001100 , using Double.ToString("F17") result 1.00000000000011000

I tried it with Double.ToString("0.0000000000000000") result 1.0000000000001100

It seems that ToString() sets all fraction numbers above the 14-th number to zero.

I am using .Net 4.5.2. How can I solve this problem.

A float and double floating point numbers ( IEEE 754 ) work on a Sign , Mantissa and Exponent in base 2 , it just so happens the number 1.000000000000113 doesn't fit into a base 2 number.

However, we do have floating point types that do work on base 10 ( decimal ), it has more precision for rational numbers, yet doesn't have the numeric range

  • float approximate Range ( ±1.5 x 10^−45 to ±3.4 x 1038 )
  • double approximate Range ( ±5.0 × 10^−324 to ±1.7 × 10308 )
  • decimal approximate Range ( ±1.0 x 10^-28 to ±7.9228 x 1028 )

Sample

double val = 1.000000000000113;
Console.WriteLine(val);
decimal val2 = 1.000000000000113m;
Console.WriteLine(val2);

Output

1.00000000000011
1.000000000000113

Full Demo Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM