Ruby中的舍入浮点数

zf2sa74q  于 2023-11-18  发布在  Ruby
关注(0)|答案(9)|浏览(193)

我有一个浮点数,我想四舍五入到小数点的百分之一。但是,我只能使用.round,这基本上将其转换为int,即2.34.round # => 2.

djmepvbi

djmepvbi1#

传递一个要舍入的参数,该参数包含要舍入到的小数位数

  1. >> 2.3465.round
  2. => 2
  3. >> 2.3465.round(2)
  4. => 2.35
  5. >> 2.3465.round(3)
  6. => 2.347

字符串

l2osamch

l2osamch2#

显示时,可以使用(例如)

  1. >> '%.2f' % 2.3465
  2. => "2.35"

字符串
如果要将其存储为舍入值,可以使用

  1. >> (2.3465*100).round / 100.0
  2. => 2.35

mcvgt66p

mcvgt66p3#

你可以用它来四舍五入到一个精确度。

  1. //to_f is for float
  2. salary= 2921.9121
  3. puts salary.to_f.round(2) // to 2 decimal place
  4. puts salary.to_f.round() // to 3 decimal place

字符串

oiopk7p5

oiopk7p54#

你可以在Float类中添加一个方法,我从stackoverflow中学到了这一点:

  1. class Float
  2. def precision(p)
  3. # Make sure the precision level is actually an integer and > 0
  4. raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
  5. # Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
  6. return self.round if p == 0
  7. # Standard case
  8. return (self * 10**p).round.to_f / 10**p
  9. end
  10. end

字符串

tvz2xvvm

tvz2xvvm5#

您还可以提供一个负数作为round方法的参数,以舍入到10、100等的最接近倍数。

  1. # Round to the nearest multiple of 10.
  2. 12.3453.round(-1) # Output: 10
  3. # Round to the nearest multiple of 100.
  4. 124.3453.round(-2) # Output: 100

字符串

8yparm6h

8yparm6h6#

(2.3465*100).round()/100.0怎么样?

js4nwp54

js4nwp547#

  1. def rounding(float,precision)
  2. return ((float * 10**precision).round.to_f) / (10**precision)
  3. end

字符串

tnkciper

tnkciper8#

如果你只需要显示它,我会使用number_with_precision助手。如果你在其他地方需要它,我会使用,正如Steve Weet指出的,round方法

qqrboqgw

qqrboqgw9#

对于ruby 1.8.7,你可以在代码中添加以下内容:

  1. class Float
  2. alias oldround:round
  3. def round(precision = nil)
  4. if precision.nil?
  5. return self
  6. else
  7. return ((self * 10**precision).oldround.to_f) / (10**precision)
  8. end
  9. end
  10. end

字符串

相关问题