use*_*662 145 ruby ruby-on-rails rounding
我有问题四舍五入.我有一个浮点数,我想要舍入到十进制的十分之一.但是,我只能使用.round哪个基本上把它变成一个int,意思2.34.round # => 2. 是有一种简单的效果方式来做类似的事情2.3465 # => 2.35
Ste*_*eet 382
将参数传递给包含要舍入的小数位数的round
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
Run Code Online (Sandbox Code Playgroud)
Pet*_*ter 177
显示时,您可以使用(例如)
>> '%.2f' % 2.3465
=> "2.35"
Run Code Online (Sandbox Code Playgroud)
如果要将其四舍五入存储,则可以使用
>> (2.3465*100).round / 100.0
=> 2.35
Run Code Online (Sandbox Code Playgroud)
你可以在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
Run Code Online (Sandbox Code Playgroud)
小智 7
你可以用它来四舍五入..
//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
Run Code Online (Sandbox Code Playgroud)