简体   繁体   English

c#将String转换为双精度损失

[英]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. ...结果是9.2233720368547758E+18 ,这不是完全相同的数字。 How should I convert string to double without loss of precision? 如何在不损失精度的情况下将字符串转换为double?

double can only guarantee 16 (approx) decimal digits of accuracy. double只能保证16(大约)十进制数字的精度。 You might try switching to decimal (which has a few more bits to play with, and holds that value with plenty of headroom). 你可能会尝试切换到decimal (它还有几个位可以使用,并保持该值具有足够的余量)。

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). 由于定义了双(( IEEE 754 )二进制浮点运算标准),因此无法将9223372036854775807转换为double精度而不会丢失精度。

By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. 默认情况下,Double值包含15个十进制数字的精度,但内部最多保留17位数。

Using Decimal will get you the precision you need here. 使用Decimal可以获得您需要的精度。 However please note that Decimal will not have the same storage range as a double. 但请注意,Decimal的存储范围不会与double相同。

See Can C# store more precise data than doubles? 请参阅Can C#存储比双精度数据更精确的数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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