在Ruby中一致的四舍五入浮点数 [英] Consistent rounding of floating points in Ruby

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

问题描述

据我所知,由于浮点的不精确表示,下面的代码感觉不一致。

I understand due to the inexact representation of floating points, the following code 'feels' inconsistent.

"%.1f" % 1.14 # => 1.1
"%.1f" % 1.15 # => 1.1
"%.1f" % 1.16 # => 1.2
"%.0f" % 1.4 # => 1
"%.0f" % 1.5 # => 2
"%.0f" % 1.6 # => 2

然而,是否有一个简单的方法来做一致的浮点五舍五入?一种方法可能是明确地进行字符串操作。是否有一个更简单的方法或存在的库?

However, is there an easy way of doing consistent floating points rounding by 5? One way might be to do string manipulation explicitly. Is there an easier way or existent library?

推荐答案

如果你想要小数精度,使用 BigDecimal ,而不是浮动。

If you want decimal precision, use BigDecimal instead of floats.

编辑:您必须在将数字传递到之前手动将数字舍入到所需的长度,否则将在转换为正常的浮点数

Edit: You will have to manually round the number to the desired length before passing it to %, otherwise it gets converted to a normal float before being rounded.

"%.1f" % BigDecimal('1.15').round(1) => "1.2"
"%.0f" % BigDecimal('1.5').round(0) => "2"

这篇关于在Ruby中一致的四舍五入浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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