c# - 乘法时的小数精度

标签 c# .net decimal precision

给定 2 个值,如下所示:

decimal a = 0.15m;
decimal b = 0.85m;

在哪里a + b永远是1.0m , 两个值都只指定到 2 个小数位并且两个值都是 >= 0.0m<= 1.0m

是否保证 x == total对于 x 的所有可能的 Decimal 值,将始终为真, ab ?使用以下计算:

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/

相关文章:

c# - 验证码 nuget 包在 ASP.NET MVC 5 上始终有效

c# - 连接字符串的最有效方法?

c# - ASP.NET 从 bin 文件夹加载非托管 dll

c# - Enum.GetNames() 导致带有负枚举常量的意外顺序

php - 小数点后0位四舍五入

c# - 创建 blob 容器时无法解析远程名称

c# - 如何在本地网络中获取 IP 地址及其具有设备 MAC 的 http 端口

.net - VisualSVN 和 VS2008 集成 - 移动文件

Java String.format 两位小数,以点作为千位分隔符,以逗号作为小数分隔符

Java 十进制格式 - 与给定的一样多的精度