我想将Double放到最接近的10。
例如,如果数字是8.0,则舍入为10.如果数字为2.0,则将其舍入为0。
发布于 2018-06-01 13:51:40
将舍入函数定义为
import Foundation
func round(_ value: Double, toNearest: Double) -> Double {
return round(value / toNearest) * toNearest
}
为你提供更一般和灵活的方式
let r0 = round(1.27, toNearest: 0.25) // 1.25
let r1 = round(325, toNearest: 10) // 330.0
let r3 = round(.pi, toNearest: 0.0001) // 3.1416
发布于 2018-06-01 14:26:26
可以使用round()
函数(将浮点数舍入到最接近的整数值):
func roundToTens(x : Double) -> Int {
return 10 * Int(round(x / 10.0))
}
用法示例:
print(roundToTens(4.9)) // 0
print(roundToTens(15.1)) // 20
在第二个例子中,15.1
除以10(1.51
),rounded(2.0
),转换为整数(2
)并再乘以10(20
)。
Swift 3:
func roundToTens(_ x : Double) -> Int {
return 10 * Int((x / 10.0).rounded())
}
func roundToTens(_ x : Double) -> Int {
return 10 * lrint(x / 10.0)
}
https://stackoverflow.com/questions/-100004694
复制相似问题