Skip to main content
 首页 » 编程设计

c# double 值显示为 .9999998

2024年02月13日12fff_TT

进一步调查后,一切归结为:

(decimal)((object)my_4_decimal_place_double_value_20.9032) 

两次转换后变成20.903199999999998


我有一个 double 值,它通过 Math.Round(...) 四舍五入到小数点后 4 位,值为 20.9032

在我的开发环境中,它是按原样显示的。

但在release环境下显示为20.903199999999998

Math.Round(...) 后没有任何操作,但值已被复制并赋值。

这怎么会发生?

更新: 数据不是从数据库加载的。

Math.Round() 的返回值分配给原始双变量。

如果此信息有帮助,Release 和 dev 是相同的架构。

请您参考如下方法:

根据 CLR ECMA 规范:

Storage locations for floating-point numbers (statics, array elements, and fields of classes) are of fixed size. The supported storage sizes are float32 and float64. Everywhere else (on the evaluation stack, as arguments, as return types, and as local variables) floating-point numbers are represented using an internal floating-point type. In each such instance, the nominal type of the variable or expression is either R4 or R8, but its value can be represented internally with additional range and/or precision. The size of the internal floating-point representation is implementation-dependent, can vary, and shall have precision at least as great as that of the variable or expression being represented. An implicit widening conversion to the internal representation from float32 or float64 is performed when those types are loaded from storage. The internal representation is typically the native size for the hardware, or as required for efficient implementation of an operation.

翻译一下,生成的IL会是一样的(除了debug模式会在地方插入nop以确保可以断点,它也可能会故意维护一个release模式认为不需要的临时变量。)...但是JITter在处理标记为调试的程序集时不那么激进。发布版本倾向于将更多的 float 值移动到 80 位寄存器中;调试版本倾向于直接从 64 位内存存储中读取。

如果您想要“精确” float 打印,请使用 string.Substring(...) 而不是 Math.Round