舍入一些数字,并将一些数字转换为int
问题描述:
我做了一个方法,它接受两个数字并返回四舍五入为三位小数的计算值。我很想知道如何将数字(如1.141
)四舍五入,但像5.0
这样的数字变成了整数(5
)。舍入一些数字,并将一些数字转换为int
代码:
def calculateHypotenuse(a,b)
if (a <= 0 || b <= 0)
return raise
end
c = Math.sqrt((a * a) + (b * b))
return c.round(3)
end
答
不知道有一个内置的花车功能,但hackish的方式可以是这样的。
def conditional_truncation(x)
x.truncate == x ? x.truncate : x
end
conditional_truncation(1.141)
=> 1.141
conditional_truncation(5.0)
=> 5