浮点值的舍入

编程入门 行业动态 更新时间:2024-10-27 10:22:59
本文介绍了浮点值的舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有 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.

更多推荐

浮点值的舍入

本文发布于:2023-10-05 09:33:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!