关于ruby:如果浮点分量不是.00 sprintf / printf,则仅显示小数点

Only show decimal point if floating point component is not .00 sprintf/printf

我很喜欢格式化浮点数,但是如果没有相关的浮点数,我希望它显示为整数。

  • 1.20-> 1.2倍
  • 1.78-> 1.78x
  • 0.80-> 0.8倍
  • 2.00-> 2倍

我可以用一些正则表达式来实现,但是想知道是否只有sprintf方式可以做到这一点?

我像这样在ruby中相当懒惰:

1
("%0.2fx" % (factor / 100.0)).gsub(/\\.?0+x$/,'x')


您要使用%g而不是%f

1
"%gx" % (factor / 100.00)


您可以像这样混合和匹配%g和%f:

1
"%g" % ("%.2f" % number)


如果您使用的是Rails,则可以使用rails'的NumberHelper方法:
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html

1
2
3
4
number_with_precision(13.001, precision: 2, strip_insignificant_zeros: true)
# => 13
number_with_precision(13.005, precision: 2, strip_insignificant_zeros: true)
# => 13.01

请注意,因为在这种情况下,精度是指小数点后的所有数字。


我以

结束

1
2
price = price.round(precision)
price = price % 1 == 0 ? price.to_i : price.to_f

这样,您甚至可以获得数字而不是字符串


这是另一种方式:

1
2
decimal_precision = 2
"%.#{x.truncate.to_s.size + decimal_precision}g" % x

或者作为一个不错的单行:

1
"%.#{x.truncate.to_s.size + 2}g" % x

我刚刚遇到了这个问题,上面的修复方法没有用,但是我想出了这个,对我有用:

1
2
3
4
5
6
7
8
9
def format_data(data_element)
    # if the number is an in, dont show trailing zeros
    if data_element.to_i == data_element
         return"%i" % data_element
    else
    # otherwise show 2 decimals
        return"%.2f" % data_element
    end
end

易于使用Rails:http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision

1
number_with_precision(value, precision: 2, significant: false, strip_insignificant_zeros: true)

我正在寻找一个函数来截断(而不是近似)Ruby on Rails中的浮点数或十进制数,我想出了以下解决方案:

你们可以在控制台中尝试,例如:

1
2
3
>> a=8.88
>> (Integer(a*10))*0.10
>> 8.8

我希望它能对某人有所帮助。
:-)