浮点值的舍入 [英] Rounding of float values

查看:54
本文介绍了浮点值的舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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屋!

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