41

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

IE

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

我可以通过一些正则表达式来实现这一点,但想知道是否有一种sprintf-only 方法可以做到这一点?

我在红宝石中相当懒惰地这样做:

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

8 回答 8

50

您想使用%g而不是%f

"%gx" % (factor / 100.00)
于 2009-05-08T03:40:17.840 回答
29

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

"%g" % ("%.2f" % number)
于 2012-03-08T22:04:21.870 回答
27

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

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

小心,因为在这种情况下,精度意味着小数点后的所有数字。

于 2013-09-03T12:26:28.460 回答
6

我结束了

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

这样你甚至可以得到数字而不是字符串

于 2014-10-02T14:15:11.967 回答
3

我刚遇到这个,上面的修复没有用,但我想出了这个,它对我有用:

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
于 2010-08-23T13:43:25.080 回答
3

这是另一种方式:

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

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

"%.#{x.truncate.to_s.size + 2}g" % x
于 2013-05-30T17:15:54.567 回答
2

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

number_with_precision(value, precision: 2, significant: false, strip_insignificant_zeros: true)
于 2018-05-15T13:14:16.813 回答
-2

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

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

>> a=8.88
>> (Integer(a*10))*0.10
>> 8.8

我希望它可以帮助某人。:-)

于 2014-01-15T23:35:12.897 回答