sprintf("%g", [float])
允许我在不指定精度的情况下格式化浮点数,以便10.00
呈现为10
而10.01
呈现为10.01
,依此类推。这很整齐。是否可以使用Rails NumberHelper方法来模拟sprintf(“%g”)的行为?
在我的应用程序中,我使用Rails NumberHelper方法呈现数字,以便我可以利用本地化功能,但我无法弄清楚如何通过这些帮助程序实现上述功能,因为他们期望明确的:precision
选项。
有没有简单的解决方法呢?
sprintf("%g", [float])
允许我在不指定精度的情况下格式化浮点数,以便10.00
呈现为10
而10.01
呈现为10.01
,依此类推。这很整齐。是否可以使用Rails NumberHelper方法来模拟sprintf(“%g”)的行为?
在我的应用程序中,我使用Rails NumberHelper方法呈现数字,以便我可以利用本地化功能,但我无法弄清楚如何通过这些帮助程序实现上述功能,因为他们期望明确的:precision
选项。
有没有简单的解决方法呢?
我已经通过在上添加另一种方法解决了这个问题10模块如下:
module ActionView
module Helpers #:nodoc:
module NumberHelper
# Formats a +number+ such that the the level of precision is determined using the logic of sprintf("%g%"), that
# is: "Convert a floating point number using exponential form if the exponent is less than -4 or greater than or
# equal to the precision, or in d.dddd form otherwise."
# You can customize the format in the +options+ hash.
#
# ==== Options
# * <tt>:separator</tt> - Sets the separator between the units (defaults to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
#
# ==== Examples
# number_with_auto_precision(111.2345) # => "111.2345"
# number_with_auto_precision(111) # => "111"
# number_with_auto_precision(1111.2345, :separator => ',', :delimiter => '.') # "1,111.2345"
# number_with_auto_precision(1111, :separator => ',', :delimiter => '.') # "1,111"
def number_with_auto_precision(number, *args)
options = args.extract_options!
options.symbolize_keys!
defaults = I18n.translate(:'number.format', :locale => options[:locale], :raise => true) rescue {}
separator ||= (options[:separator] || defaults[:separator])
delimiter ||= (options[:delimiter] || defaults[:delimiter])
begin
number_with_delimiter("%g" % number,
:separator => separator,
:delimiter => delimiter)
rescue
number
end
end
end
end
end
它与%g
选项如上面在代码注释中描述这使得数number_with_delimiter
特定呼叫。
这对我很好,但我很乐意考虑这个解决方案。
为什么不使用Ruby的Kernel::sprintf和NumberHelper?推荐使用与this syntax:str % arg
其中str
是格式字符串(%g
你的情况):
>> "%g" % 10.01
=> "10.01"
>> "%g" % 10
=> "10"
然后你可以使用NumberHelper打印只是货币符号:
>> foo = ActionView::Base.new
>> foo.number_to_currency(0, :format => "%u") + "%g"%10.0
=> "$10"
和定义自己的便利方法:
def pretty_currency(val)
number_to_currency(0, :format => "%u") + "%g"%val
end
pretty_currency(10.0) # "$10"
pretty_currency(10.01) # "$10.01"
谢谢,但这并没有达到我所需要的。具体来说,我需要根据用户的当前语言环境使用不同分隔符和分隔符格式化的数字。所以基本上我需要在NumberHelper方法本身中使用“%g”,这是不可能覆盖的。我将发布我的解决方法作为答案。 – Olly
对我来说很不错 – klochner