简体   繁体   中英

doublevalue.ToString() loses decimal places in C#

The ToString() of a double value, causes losing of the decimal places

(1521.6666666666667).ToString()   ==>  "1521.66666666667"

Is there any way to save all the decimal places when converting to string

Also

(1521.6666666666667).ToString("F13");   => "1521.6666666666700"
(1521.6666666666667).ToString("0.0000000000000");   => "1521.6666666666700

Does this have to do with size of the double value

The solution to this is reading the documentation. Seriously It is NOT "ToString" that is loosing it.

Let me quote the float data Type from https://msdn.microsoft.com/en-us/library/b1e65aza.aspx :

Precision: 7 digits.

The numbers are in your source, they are never in the float. Not properly. The value is rounded.

decimal d = 1521.6666666666667M;
d.ToString();

According to the documentation :

Compared to floating-point types, the decimal type has more precision and a smaller range.

Specifically, decimal has 28-29 significant digits, rather than 15-16 for double .

您必须格式化字符串。

(1521.6666666666667).ToString("R");

You can use Decimal instead of Double :

  (1521.6666666666667M).ToString(); // note "M"

Another possibility (if you have to use Double ) is "R" format:

 (1521.6666666666667).ToString("R");

Use The Round-trip ("R") Format Specifier , which will attempts to ensure that a numeric value that is converted to a string is parsed back into the same numeric value. This format is supported only for the Single , Double , and BigInteger types.

But for Double and Single values, the "R" format specifier in some cases fails to successfully round-trip the original value and also offers relatively poor performance. Instead, we recommend that you use the "G17" format specifier for Double values and the "G9" format specifier to successfully round-trip Single values.

From MSDN:

In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems.

Resource: Standard Numeric Format Strings .

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