给定 2 个值,如下所示:
decimal a = 0.15m;
decimal b = 0.85m;
在哪里a + b
永远是1.0m
, 两个值都只指定到 2 个小数位并且两个值都是 >= 0.0m
和 <= 1.0m
是否保证 x == total
对于 x
的所有可能的 Decimal 值,将始终为真, a
和 b
?使用以下计算:
decimal x = 105.99m;
decimal total = (x * a) + (x * b);
或者在某些情况下 x == total
只保留 2 位小数,但不能超过 2 位小数?
如果 a
会有什么不同吗?和 b
可以指定为无限小数位(尽可能多 Decimal
允许),但只要 a + b = 1.0m
还成立吗?
最佳答案
小数存储为符号、整数和表示小数位置的数字 10 的整数指数。只要数字的整数部分(例如 105.99 中的 105)不够大,那么 a + b 将始终等于 1。等式 (x * a) + (x * b) 的结果将始终具有四位小数的正确值。
与 float 和 double 不同,精度不会丢失到数据类型的大小(128 位)
来自 MSDN:
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding. For example, the following code produces a result of 0.9999999999999999999999999999 rather than 1
decimal dividend = Decimal.One;
decimal divisor = 3;
// The following displays 0.9999999999999999999999999999 to the console
Console.WriteLine(dividend/divisor * divisor);
关于c# - 乘法时的小数精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14139941/