Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float number format without rounding in ruby

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

like image 550
Nodir Nasirov Avatar asked Dec 18 '22 20:12

Nodir Nasirov


2 Answers

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
like image 51
shivam Avatar answered Dec 27 '22 11:12

shivam


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"
like image 40
Aleksei Matiushkin Avatar answered Dec 27 '22 12:12

Aleksei Matiushkin