📜  快速将双精度舍入到小数点后 2 位 - Swift 代码示例

📅  最后修改于: 2022-03-11 15:01:02.484000             🧑  作者: Mango

代码示例1
You can use Swift's round function to accomplish this.

To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y)  // 1.236
Other than any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double.

EDIT:
Regarding the comments that it sometimes does not work, please read this: