无零小数点后的Ruby浮点数

5

我曾经进行了很多搜索,以获取在小数点后不带有不需要的零的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`。我能否在不改变类型的情况下获取浮点值?
8个回答

8

尝试:

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

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

6
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

6

我通过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
我建议使用类似以下的内容。
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父类添加一个方法,以便该方法也可以与整数(Fixnum)一起使用。使用==进行比较,因为它在比较之前不会进行类型转换。
class Numeric
  def slim(places = nil)
    truncate == self ? truncate : places.nil? ? self : round(places)
  end
end

1
假设您想删除零,仅当它完全由零组成时,并返回原始值,我会执行以下操作:
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

0
更加详细:
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

0

您是想要获取浮点数的整数部分吗?

123.0 的整数部分是 123,156.78 的整数部分是 156。

如果是的话,代码如下:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接