使用 ToString() 格式化时舍入小数和双精度之间的差异 [英] Rounding differences between decimal and double when formatting with ToString()

查看:24
本文介绍了使用 ToString() 格式化时舍入小数和双精度之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 ToString("F2") 格式化数值时,我发现结果存在差异.

I am seeing differences in the result when formatting numeric values using ToString("F2").

0.125m.ToString("F2", CultureInfo.InvariantCulture); // 0.13
0.125.ToString("F2", CultureInfo.InvariantCulture); // 0.12

为什么这些值的四舍五入不同?

Why are these values rounded differently?

.NET Fiddle 版本的代码这里.

.NET Fiddle version of the code here.

推荐答案

已记录在案 此处:

当精度说明符控制结果字符串中的小数位数时,结果字符串反映一个四舍五入为最接近无限精确结果的可表示结果的数字.如果有两个同样接近的可表示结果:

When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:

  • 在 .NET Framework 和 .NET Core 到 .NET Core 2.0 上,运行时选择具有较大最低有效数字的结果(即,使用 MidpointRounding.AwayFromZero).
  • 在 .NET Core 2.1 及更高版本上,运行时选择具有最低有效数字的结果(即,使用 MidpointRounding.ToEven).

请注意,double 是浮点二进制小数点类型.它们以二进制系统表示(如 11010.00110).当 double 以十进制表示时,它只是一种近似值,因为并非所有二进制数都在十进制中具有精确表示.

Note that double is a floating binary point type. They are represented in binary system (like 11010.00110). When double is presented in decimal system it is only an approximation as not all binary numbers have exact representation in decimal system.

这篇关于使用 ToString() 格式化时舍入小数和双精度之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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