指定小数点后的位数

时间:2022-02-24 19:20:08
 a = '60.950'
 b = a.to_f

 puts a # => 60.950
 puts b # => 60.95

I want to display three digits after the decimal point everytime. How can I force 0 at the end of b?

每次我都想在小数点后显示三位数。我怎么能在b的末尾强制0 ?

2 个解决方案

#1


12  

Use sprintf.

使用sprintf。

sprintf('%.3f', 60.95)
# => "60.950"

#2


4  

Use the mother of the formatting methods, such as String#% or printf or sprintf, which is Kernel#format

使用格式化方法的母亲,如字符串#%或printf或sprintf,这是内核#格式。

puts format('%.3f', 0)

The others refer to this, and the Kernel#format documentation has the full documentation tables.

其他的引用了这个,内核#格式文档有完整的文档表。

#1


12  

Use sprintf.

使用sprintf。

sprintf('%.3f', 60.95)
# => "60.950"

#2


4  

Use the mother of the formatting methods, such as String#% or printf or sprintf, which is Kernel#format

使用格式化方法的母亲,如字符串#%或printf或sprintf,这是内核#格式。

puts format('%.3f', 0)

The others refer to this, and the Kernel#format documentation has the full documentation tables.

其他的引用了这个,内核#格式文档有完整的文档表。