Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想要任何四舍五入的项目,例如:
(5.101 * 100).round / 100.0
要像这样输出:
5.10
而不是这个:
5.1
我如何在 Ruby 中做到这一点?
有几种方法,但我更喜欢使用字符串的%(格式)运算符:
%
'%.2f' % [(5.101 * 100).round / 100.0] # => "5.10"
内核的sprintf方法具有各种标志和修饰符的文档。还有内核的printf,但就像我说的,我会选择%.
sprintf
printf
我希望它会帮助你。
2.0.0p195 :002 > (52.452158744).round(2) => 52.45 2.0.0p195 :003 > (20.452158744).round(2) => 20.45 2.0.0p195 :004 > (20.002555).round(2) => 20.0 2.0.0p195 :005 > (20.012555).round(2) => 20.01