C# double to decimal precision loss

后端 未结 3 1335
天涯浪人
天涯浪人 2020-12-09 01:59

I have a double \"138630.78380386264\" and I want to convert it to a decimal, however when I do so I do it either by casting or by using Convert.ToDecimal

3条回答
  •  执笔经年
    2020-12-09 02:16

    138630.78380386264 is not exactly representable to double precision. The closest double precision number (as found here) is 138630.783803862635977566242218017578125, which agrees with your findings.

    You ask why the conversion to decimal does not contain more precision. The documentation for Convert.ToDecimal() has the answer:

    The Decimal value returned by this method contains a maximum of 15 significant digits. If the value parameter contains more than 15 significant digits, it is rounded using rounding to nearest. The following example illustrates how the Convert.ToDecimal(Double) method uses rounding to nearest to return a Decimal value with 15 significant digits.

    The double value, rounded to nearest at 15 significant figures is 138630.783803863, exactly as you show above.

提交回复
热议问题