仅当浮点分量不是 .00 sprintf/printf 时才显示小数点
-
10-07-2019 - |
题
我很好地格式化了一个浮点数,但如果没有相关的浮点数,我希望它显示为整数。
IE。
- 1.20 -> 1.2 倍
- 1.78 -> 1.78x
- 0.80 -> 0.8x
- 2.00 -> 2x
我可以用一些正则表达式来实现这一点,但想知道是否有一个 sprintf
- 这样做的唯一方法?
我在 ruby 中相当懒惰地这样做:
("%0.2fx" % (factor / 100.0)).gsub(/\.?0+x$/,'x')
解决方案
你想使用 %g
代替 %f
:
"%gx" % (factor / 100.00)
其他提示
您可以混合并匹配 %g 和 %f,如下所示:
"%g" % ("%.2f" % number)
如果您使用的是 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
请小心,因为在这种情况下,精度意味着小数点后的所有数字。
我最终得到
price = price.round(precision)
price = price % 1 == 0 ? price.to_i : price.to_f
这样你甚至可以得到数字而不是字符串
我刚刚遇到这个问题,上面的修复不起作用,但我想出了这个,这对我有用:
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
这是另一种方法:
decimal_precision = 2
"%.#{x.truncate.to_s.size + decimal_precision}g" % x
或者作为一句漂亮的话:
"%.#{x.truncate.to_s.size + 2}g" % x
轻松使用 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)
我正在寻找一个在 Ruby on Rails 中截断(不是近似)浮点数或十进制数的函数,我找到了以下解决方案:
你们可以在控制台中尝试,例如:
>> a=8.88
>> (Integer(a*10))*0.10
>> 8.8
我希望它对某人有帮助。:-)
不隶属于 StackOverflow