Domanda

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?

È stato utile?

Soluzione 3

Well I got my answer through Sawa's and BroiSatse's answers.

But I guess following is enough to get what I required:

irb(main):057:0> num = 14.0
=> 14.0
irb(main):058:0> num = num == num.to_i ? num.to_i : num
=> 14
irb(main):059:0> num = 14.1
=> 14.1
irb(main):060:0> num = num == num.to_i ? num.to_i : num
=> 14.1

Altri suggerimenti

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

Assuming that you want to remove the zeros, only if it contains purely zeros and otherwise return the original value, I would do

num = 123.00
(num.to_s.scan(/[.]\d+/)[0].to_f > 0) ? num : num.to_i #=> 123

num = 123.45
(num.to_s.scan(/[.]\d+/)[0].to_f > 0) ? num : num.to_i #=> 123.45

I would suggest something like

class Float
  def custom_format(num)
    num.round(0) == num ? num : num.round(1)
  end
end

13.1.custom_format #=> 13.1
13.7.custom_format #=> 13.7
13.0.custom_format #=> 13

I would like to add a method to Numeric parent class so that this method can also be used with Integer(Fixnum) numbers. Using == to do comparison as it does not do typecasting before comparing.

class Numeric
  def slim(places = nil)
    truncate == self ? truncate : places.nil? ? self : round(places)
  end
end

Would you be asking for the Integer part of the float value?

Integer part of 123.0 is 123 and of 156.78 is 156.

If so, It'd be:

2.1.0 :001 > 123.0.to_i
 => 123
2.1.0 :002 > 156.7.to_i
 => 156

More descriptive:

number = 14.0
BigDecimal.new(number.to_s).frac.zero? ? number.to_i : number
# => 14    

number = 14.1
BigDecimal.new(number.to_s).frac.zero? ? number.to_i : number
# => 14.1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top