scala 如果不是整数,如何四舍五入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32298393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to round up a number if it's not an integer?
提问by nick shmick
I want to calculate a simple number, and if the number is not an integer I want to round it up.
我想计算一个简单的数字,如果这个数字不是整数,我想把它四舍五入。
For instance, if after a calculation I get 1.2, I want to change it to 2. If the number is 3.7, I want to change it to 4and so on.
例如,如果在计算后得到1.2,我想将其更改为2。如果号码是3.7,我想把它改成4等等。
回答by Peter Neyens
You can use math.ceilto round a Doubleup and toIntto convert the Doubleto an Int.
您可以使用向上math.ceil舍入并将 转换为。DoubletoIntDoubleInt
def roundUp(d: Double) = math.ceil(d).toInt
roundUp(1.2) // Int = 2
roundUp(3.7) // Int = 4
roundUp(5) // Int = 5
回答by olisteadman
Having first imported mathimport scala.math._(the final dot & underscore are crucial for what comes next)
首先导入数学import scala.math._(最后的点和下划线对接下来的内容至关重要)
you can simply writeceil(1.2)
floor(3.7)
你可以简单地写ceil(1.2)
floor(3.7)
plus a bunch of other useful math functions likeexp(1)
pow(2,2)
sqrt(pow(2,2)
加上一堆其他有用的数学函数,比如exp(1)
pow(2,2)
sqrt(pow(2,2)

