【问题标题】:Ruby: counting digits in a float numberRuby:计算浮点数中的数字
【发布时间】:2009-10-02 20:10:49
【问题描述】:

是否有任何有价值的 Ruby 方法来计算浮点数中的位数?另外,如何指定精确的 to_s 浮点数?

【问题讨论】:

  • 请记住,浮点十进制表示中的完整位数不一定是有用的数字。例如,0.1 不能以二进制精确表示,因此您可能不会特别高兴地发现 0.1 有 18 位不四舍五入。

标签: ruby string floating-point digits


【解决方案1】:
# Number of digits

12345.23.to_s.split("").size -1 #=> 7

# The precious part

("." + 12345.23.to_s.split(".")[1]).to_f #=> .023

# I would rather used 
# 12345.23 - 12345.23.to_i 
# but this gives 0.22999999999563

【讨论】:

  • 您计算数字的解决方案没有考虑到负数上的'-'。另外,你为什么要做to_s.split("").size 而不是只做to_s.size
【解决方案2】:

在 Ruby 中指定浮点数的精度。你可以使用round方法。

number.round(2)

2 是精度。

53.819.round(2) -> 53.82

【讨论】:

  • 就像 rails number_with_precision(precision: 3) 一样 "%.3f" % 53.82 => "53.820"
【解决方案3】:

我认为您应该查看 number_with_precision 助手。

number_with_precision(13, :precision => 5) # => 13.00000

【讨论】:

  • 我正在寻找 Ruby 解决方案,而不是 Rails
猜你喜欢
  • 2011-01-10
  • 2014-08-16
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2014-03-12
相关资源
最近更新 更多