为什么Convert.ToDecimal(双)到15个有效数字? [英] Why does Convert.ToDecimal(Double) round to 15 significant figures?

查看:1445
本文介绍了为什么Convert.ToDecimal(双)到15个有效数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 double ,小数点后17位,即:

I have a double with 17 digits after the decimal point, i.e.:

double myDouble = 0.12345678901234567;

如果我把它转换成一个十进制这个:

If I convert this to a decimal like this:

decimal myDecimal = Convert.ToDecimal(myDouble);

然后 myDecimal 的值被舍入,根据 Convert.ToDecimal 文档,到15位数(即 0.0123456789012345 )。我的问题是,为什么这个四舍五入执行?

then the value of myDecimal is rounded, as per the Convert.ToDecimal documentation, to 15 digits (i.e. 0.0123456789012345). My question is, why is this rounding performed?

我明白,如果我的原始号码可以准确地表示在10号,我试图将它存储为code> double ,那么我们只能对前15位数字有信心。最后两位数字将受到舍入误差的影响。但是,这是10个偏见的观点。我的号码可能更准确地表示为一个 double ,我希望将其转换为 decimal ,同时保持准确性

I understand that if my original number could be accurately represented in base 10 and I was trying to store it as a double, then we could only have confidence in the first 15 digits. The final two digits would be subject to rounding error. But, that's a base 10 biased point of view. My number may be more accurately represented by a double and I wish to convert it to decimal while preserving as much accuracy as possible.

不应该 Convert.ToDecimal 旨在最大限度地减少 myDouble (double)Convert.ToDecimal(myDouble)

Shouldn't Convert.ToDecimal aim to minimise the difference between myDouble and (double)Convert.ToDecimal(myDouble)?

推荐答案

Double 的文档:


尽管a
最多为17位数字,双精度值最多为<15>十进制精度<因为double值本身最多有15个小数位,所以将其转换为十进制将产生一个十进制数值,这个值将被保留在内部

A Double value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally

有15个有效数字。

这篇关于为什么Convert.ToDecimal(双)到15个有效数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆