// Purpose: Determine attendance based on ticket-price
// Example: attendance(4.90) == 135
def attendance: Double => Int = {
(ticket_price: Double) => {
120 + math.ceil(150 * (5.00 - ticket_price)).toInt
}
} //> attendance: => Double => Int
attendance(4.90) //> res0: Int = 135
assert(attendance(4.90) == 135)
基本上断言被炸毁了,出勤率返回了 134 而不是 135。所以我把 math.ceil 放在它上面并且它起作用了。但我只是想知道这是否是最好/适当/惯用的方法。
对于那些想知道这段代码来自哪里的人:attendance code
最佳答案
处理货币时,不应使用 float/double 类型。我知道这些方法:
使用整数(即 Short、Int、Long 等)和尽可能小的值(例如 cents、satoshis 等)。 Scala 中的值类可能会增强这一点。
使用像 BigDecimal 这样的精确算术。
使用任意精度的定点算法。 (这个和a基本一样。)
请注意,在处理货币时应注意整数溢出。
关于scala - 在 Scala 中舍入 double 或 float 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20167089/