简体   繁体   中英

c# Convert String to double loss of precision

I have the following:

string value = "9223372036854775807";
double parsedVal = double.Parse(value, CultureInfo.InvariantCulture);

... and the result is 9.2233720368547758E+18 which is not the exact same number. How should I convert string to double without loss of precision?

double can only guarantee 16 (approx) decimal digits of accuracy. You might try switching to decimal (which has a few more bits to play with, and holds that value with plenty of headroom).

You can't convert 9223372036854775807 to double without loss of precision, due to the definition of a double (( IEEE 754 ) standard for binary floating-point arithmetic).

By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally.

Using Decimal will get you the precision you need here. However please note that Decimal will not have the same storage range as a double.

See Can C# store more precise data than doubles?

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