在 Ruby 中设置浮点数的显示精度

发布于 2024-08-15 08:48:54 字数 215 浏览 2 评论 0原文

是否可以在 Ruby 中设置浮点数的显示精度?

比如:

z = 1/3
z.to_s    #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333

或者我是否必须重写Floatto_s方法?

Is it possible to set the display precision of a float in Ruby?

Something like:

z = 1/3
z.to_s    #=> 0.33333333333333
z.to_s(3) #=> 0.333
z.to_s(5) #=> 0.33333

Or do I have to override the to_s method of Float?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

你不是我要的菜∠ 2024-08-22 08:48:54

z.round(2)x.round(3) 是最简单的解决方案。请参阅 http://www.ruby-doc。 org/core-1.9.3/Float.html#method-i-round

也就是说,这只能确保它不超过那么多位数。对于 1/3 来说没问题,但如果您说 0.25.round(3),您将得到 0.25,而不是 0.250。

z.round(2) or x.round(3) is the simplest solution. See http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round.

That said, that will only ensure that it is no more than that many digits. In the case of 1/3 that is fine, but if you had say 0.25.round(3) you will get 0.25, not 0.250.

渔村楼浪 2024-08-22 08:48:54

您可以使用 sprintf:

sprintf("%0.02f", 123.4564564)

You can use sprintf:

sprintf("%0.02f", 123.4564564)
晨光如昨 2024-08-22 08:48:54

我通常只会在开放代码中进行转换,例如:

puts "%5.2f" % [1.0/3.0] 

Ruby 调用 Kernel#format 对于这样的表达式,因为 String 有一个 核心操作符%定义就可以了。如果这对您有任何启发,请将其视为Ruby 的 printf

I would normally just do the conversion in open code, something like:

puts "%5.2f" % [1.0/3.0] 

Ruby calls Kernel#format for expressions like this, because String has a core operator % defined on it. Think of it as printf for Ruby if that rings any bells for you.

风轻花落早 2024-08-22 08:48:54

Rubocop 建议使用 #format #sprintf 并使用带注释的字符串标记。

#format 的语法

%[flags][width][.precision]type

示例:

# Ensure we store z as a float by making one of the numbers a float.
z = 1/3.0

# Format the float to a precision of three.
format('%<num>0.3f', num: z)
# => "0.333"

format('%<num>0.5f', num: z)
# => "0.33333"

# Add some text to the formatted string
format('I have $%<num>0.2f in my bank account.', num: z)
# => "I have $0.33 in my bank account."

参考文献:

Rubocop recommends using #format over #sprintf and using annotated string tokens.

The syntax for #format is

%[flags][width][.precision]type

Example:

# Ensure we store z as a float by making one of the numbers a float.
z = 1/3.0

# Format the float to a precision of three.
format('%<num>0.3f', num: z)
# => "0.333"

format('%<num>0.5f', num: z)
# => "0.33333"

# Add some text to the formatted string
format('I have $%<num>0.2f in my bank account.', num: z)
# => "I have $0.33 in my bank account."

References:

痞味浪人 2024-08-22 08:48:54

您可以使用看跌期权

z = #{'%.3f' % z}

You can use puts

z = #{'%.3f' % z}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文