How to convert a float into a desired precision, then convert it to bigdecimal? (correct way?)

Following is a example:

require "big"

x = 100/20.45
p! x # 4.88997555012225
p! typeof(x) # Float64

x1 = sprintf("%.2f", x)
p! x1 # 4.89
p! typeof(x1) # String

x2 = BigDecimal.new(x1)
p! x2 # => 4.89
p! typeof(x2) # BigDecimal

I guess there maybe a better solution?

Yeah, there’s no need to go through string for this. You can just use Number#round to round the value.
I’d recommend converting to BigDecimal first and then round that big decimal, though. This avoids any surprises with floating point precision.

require "big"
x = 100 / 20.45
x.to_big_d.round(2) # => 4.89
3 Likes

Oops, i miss those methods defined in superclass Number …

Thank you.