浮点值的舍入 [英] Rounding of float values
问题描述
我有 double
值,如 12.256852651
,我想将其显示为 12.257
作为浮点数而不将其转换为字符串类型。
I have the double
value like 12.256852651
and I want to display it as 12.257
as a float number without converting it in to a string type.
如何在C#中实现?
推荐答案
我首先将其转换为十进制
,然后使用 Math.Round
上的结果。这种转换不是严格必须的,但是如果在使用二进制浮点数时四舍五入到小数位,我总是会感到不安。
I'd first convert to Decimal
and then use Math.Round
on the result. This conversion is not strictly necessary, but I always feel a bit uneasy if I round to decimal places while using binary floating points.
Math.Round((Decimal)f, 3, MidpointRounding.AwayFromZero)
您还应该查看 MidpointRounding
,因为默认情况下,此操作使用的是Banker的回合,这不是您上学以来所习惯的。
You should also look into the choice of MidpointRounding
, since by default this uses Banker's round, which is not what you are used to from school.
这篇关于浮点值的舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!