Ruby 中的舍入浮点数

问题描述 投票:0回答:9

我在舍入时遇到问题。我有一个浮点数,我想将其四舍五入到小数点后百分之几。但是,我只能使用

.round
,它基本上将其转换为 int,这意味着
2.34.round # => 2.
有没有一种简单的效果方法可以做类似
2.3465 # => 2.35

的事情
ruby-on-rails ruby rounding
9个回答
413
投票

将参数传递给 round,其中包含要舍入的小数位数

>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347

190
投票

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

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

如果你想将其存储为四舍五入,你可以使用

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

12
投票

您可以使用它来四舍五入到精度..

//to_f is for float

salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place                   

puts salary.to_f.round() // to 3 decimal place          

7
投票

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

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

4
投票

您还可以提供一个负数作为

round
方法的参数,以四舍五入到最接近的 10、100 等的倍数。

# Round to the nearest multiple of 10. 
12.3453.round(-1)       # Output: 10

# Round to the nearest multiple of 100. 
124.3453.round(-2)      # Output: 100

3
投票

(2.3465*100).round()/100.0
呢?


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

1
投票

如果您只需要显示它,我会使用 number_with_ precision 帮助器。 如果你在其他地方需要它,我会使用,正如 Steve Weet 指出的,

round
方法


0
投票

对于 ruby 1.8.7,您可以将以下内容添加到代码中:

class Float
    alias oldround:round
    def round(precision = nil)
        if precision.nil?
            return self
        else
            return ((self * 10**precision).oldround.to_f) / (10**precision)
        end 
    end 
end
© www.soinside.com 2019 - 2024. All rights reserved.