Ruby圆整数,长度不同

时间:2013-02-19 07:24:45

标签: ruby rounding

我可以有不同长度的整数... 例如1896年,或894年......

但是我如何将它们转换为浮点数,以便逗号后只有一个符号?

例如

1896 -> 1.9
894 -> 0.9
539 -> 0.5

我如何在红宝石上做到这一点?

现在我这样做:

type.TYP_CCM.round(-2).to_s[0].concat(".").concat(type.TYP_CCM.round(-2).to_s[1])

但这不是一个好主意,只适用于4位数字...

2 个答案:

答案 0 :(得分:2)

那是怎么回事:

(1896/1000.0).round(1) # 1.9
(894/1000.0).round(1) # 0.9
(539/1000.0).round(1) # 0.5

答案 1 :(得分:1)

这一切都在API中:

(1234/1000.0).round(1)

应该在点后面给你一个十进制数字。

即使它不在API中,您也可以通过

轻松模拟它
(1234/100.0).round() / 10.0

或更接近您的代码:

(1234).round(-2) / 1000.0

至于确保您的输出格式为xxxx.y - 使用格式字符串http://www.ruby-doc.org/core-1.9.3/String.html#method-i-25