Ruby: Controlling printing in scientific notation

前端 未结 2 978
庸人自扰
庸人自扰 2021-02-12 12:48

If I have an extremely long floating point number in Ruby such as:

 x = 123456789012345.to_f

when it is displayed, say, via to_s,

相关标签:
2条回答
  • 2021-02-12 13:26

    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" 
    
    0 讨论(0)
  • 2021-02-12 13:27

    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.

    0 讨论(0)
提交回复
热议问题