Ruby-乘法问题 [英] Ruby - Multiplication issue

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

问题描述

我的输出是这样的-

ruby-1.9.2-p290 :011 > 2.32 * 3
=> 6.959999999999999

我记得有一段时间我回到了另一台机器上,就像.. 2.32 * 3 = 6

And I remember sometime back on another machine I had got it like.. 2.32 * 3 = 6

我的错误是什么? 非常感谢您阅读本文. :)

What is my mistake? Thanks a ton for reading this. :)

推荐答案

如果您真的想舍入为整数,则只需

If you really want to round down to an integer then just

(3 * 2.32).to_i

但是我认为这不太可能.通常,您只想将稍微不精确的浮点数格式化为这样的格式

but I think that's unlikely. Usually you just want to format the slightly imprecise floating point number to something like this

"%0.2f" % (3 * 2.32) 
=> "6.96"

如果您真的想使用确切的表示形式,则可以使用 BigDecimal .

If you really want to work with the exact representation then you can use BigDecimal.

require 'BigDecimal'
(3 * BigDecimal.new("2.32")).to_s("F")
=> "6.96"

PS.建议阅读 http://floating-point-gui.de/ DS.

PS. Recommended read http://floating-point-gui.de/ DS.

这篇关于Ruby-乘法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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