How to round a very small floating point number with trailing zeros?

Viewed 134

Currently my code renders the number:

x = 0.000092627861766
p x

as something like a BigInt format such that:

=> 9.0e-05 

Is there a method I can call on the variable to return a rounded floating point number (in either number or string format) such that:

x.some_method
# Always show N number of digits after the initial decimal point.
=> 0.00009263 
OR 
=> "0.00009263"
2 Answers

you can set the number of digits to be shown:

p "%0.08f" % x # => "0.00009263"

You can define a new method to do that. I use BigDecimal just for accuracy and prevent unexpected result, but I think you can do the probably the same thing in Float:

require 'bigdecimal'
class BigDecimal
  def round_after_n(n)
    round(self.exponent.abs + n + 1)
  end
end
x = BigDecimal('0.000092627861766')
#  => 0.926279e-4 
x.round_after_n(5).to_s('F')
#  => "0.0000926279"
Related