There is a float number num = 22.0098
. How can I format it to limit 3 digits after floating point? I tried sprintf('%.3f',num)
but return is 22.010
, I need 22.009
though
I can think of using bigdecimal. Not sure though if its an overkill:
require 'bigdecimal'
BigDecimal::new("22.0098").truncate(3).to_f
#=> 22.009
Unfortunately, unlike Float#round
, Float#floor
does not accept an amount of digits. The below code implements the desired behaviour.
def floor_float input, digits = 3
input.divmod(10 ** -digits).first / (10 ** digits).to_f
end
This might be used as monkey patch:
class Float
def floor_ext digits = 3
self.divmod(10 ** -digits).first / (10 ** digits).to_f
end
end
22.0098.floor_ext
#⇒ 22.009
Probably more succinct variant as suggested by @Stefan:
class Float
def floor_ext digits = 3
div(10 ** -digits).fdiv(10 ** digits)
end
end
22.0098.floor_ext
#⇒ 22.009
Or, one might deal with strings explicitly:
i, f = 22.0098.to_s.split('.')
#⇒ [ "22", "0098" ]
[i, f[0..2]].join('.')
#⇒ "22.009"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With