If I have an extremely long floating point number in Ruby such as:
如果我在Ruby中有一个非常长的浮点数,例如:
x = 123456789012345.to_f
when it is displayed, say, via to_s
, it appears in scientific notation:
当它显示时,例如,通过to_s,它以科学记数显示:
"1.23456789012345e+14"
Is there any way to suppress the formatting in scientific notation, or on the other side of the coin, force it for extremely short floating point numbers?
有没有办法抑制科学记数法中的格式化,或硬币的另一面,强迫它为极短的浮点数?
2 个解决方案
#1
19
You can do all sorts of things using the %
operator. For example:
您可以使用%运算符执行各种操作。例如:
x = 123456789012345.to_f
"%f" % x # => "123456789012345.000000"
y = 1.23
"%E" % y # => "1.230000E+000"
The various options are the same as for the sprintf function.
各种选项与sprintf函数相同。
#2
2
Just for convenience you can also control number of digits after decimal point. So do:
为方便起见,您还可以控制小数点后的位数。所以:
x = 1.234598
"%.3E" % x=> "1.235E+00"
Another neat thing you can do is pad with space from left like this:
你可以做的另一个巧妙的事情是从左边填充空间,如下所示:
x = 1.234
"%10.3E" % x => " 1.234E+00"
#1
19
You can do all sorts of things using the %
operator. For example:
您可以使用%运算符执行各种操作。例如:
x = 123456789012345.to_f
"%f" % x # => "123456789012345.000000"
y = 1.23
"%E" % y # => "1.230000E+000"
The various options are the same as for the sprintf function.
各种选项与sprintf函数相同。
#2
2
Just for convenience you can also control number of digits after decimal point. So do:
为方便起见,您还可以控制小数点后的位数。所以:
x = 1.234598
"%.3E" % x=> "1.235E+00"
Another neat thing you can do is pad with space from left like this:
你可以做的另一个巧妙的事情是从左边填充空间,如下所示:
x = 1.234
"%10.3E" % x => " 1.234E+00"