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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:32:06  来源:igfitidea点击:

How to round up a number if it's not an integer?

scaladoubleceil

提问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 math
import scala.math._(the final dot & underscore are crucial for what comes next)

首先导入数学
import scala.math._(最后的点和下划线对接下来的内容至关重要)

you can simply write
ceil(1.2) floor(3.7)

你可以简单地写
ceil(1.2) floor(3.7)

plus a bunch of other useful math functions like
exp(1) pow(2,2) sqrt(pow(2,2)

加上一堆其他有用的数学函数,比如
exp(1) pow(2,2) sqrt(pow(2,2)

回答by Xavier Guihot

The ceilfunction is also directly accessible on the Double:

ceil功能也可以直接访问Double

3.7.ceil.toInt // 4