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?
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
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
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