Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby float without any zero after decimal point

I had searched a lot to get my exact requirement for getting the float value without unwanted zero after decimal.

Eg:  14.0 should be 14
     14.1 should be 14.1

Nearest possible solution I found so far is using sprintf():

irb(main):050:0> num = 123.0
=> 123.0
irb(main):051:0> sprintf('%g', num)
=> "123"

Problem here is my num type changed to String from Float. Can I get the float value change without its type changed?

like image 925
brg Avatar asked Nov 30 '22 11:11

brg


2 Answers

Try:

class Float
  def try_integer
    to_i == self ? to_i : self
  end
end

14.2.try_integer    #=> 14.2
14.0.try_integer    #=> 14
like image 179
BroiSatse Avatar answered Dec 24 '22 16:12

BroiSatse


14.0.tap{|x| break x.to_i == x ? x.to_i : x}
# => 14

14.1.tap{|x| break x.to_i == x ? x.to_i : x}
# => 14.1
like image 42
sawa Avatar answered Dec 24 '22 18:12

sawa