2014-04-07 45 views
2

我已经搜索了很多,以得到我确切的要求,以获得float值,小数点后没有不需要的零。红宝石浮动小数点后没有任何零点

Eg: 14.0 should be 14 
    14.1 should be 14.1 

最近可能的解决方案,我发现到目前为止使用sprintf()

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

问题,这里是我num类型从Float改为String。 我可以在没有更改类型的情况下获得浮动值更改吗?

回答

2

那么我通过Sawa和BroiSatse的答案得到了我的答案。

但我想下面是足以让我需要什么:

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 
1

你会问浮点数的整数部分吗? 123.0

整数部分是123和156.78是156

如果是的话,这将会是:

2.1.0 :001 > 123.0.to_i 
=> 123 
2.1.0 :002 > 156.7.to_i 
=> 156 
5
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 
+2

这甚至更好。 – Bala

5

尝试:

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

14.2.try_integer #=> 14.2 
14.0.try_integer #=> 14 
0

假设你想删除零,只有当它包含我会做

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 
1

我建议像

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 
1

我想一个方法添加到Numeric父类,因此,这种方法也可以与Integer(Fixnum)号码一起使用。使用==进行比较,因为在比较之前它不会进行类型转换。

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