BMI计算Xcode
BMI计算Xcode
请问有谁知道如何在Swift中将double值四舍五入到x位小数?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime
是一个以秒为单位的NSTimeInterval(double)。
totalWorkTimeInHours
会给我小时数,但它会给我一个非常长的精确数字,比如1.543240952039......
当我打印totalWorkTimeInHours
时,如何将其四舍五入到,比如1.543?
admin 更改状态以发布 2023年5月21日
Swift 2扩展
以下是一种更为通用的解决方案,适用于Swift 2和iOS 9:
extension Double { /// Rounds the double to decimal places value func roundToPlaces(places:Int) -> Double { let divisor = pow(10.0, Double(places)) return round(self * divisor) / divisor } }
Swift 3扩展
在Swift 3中,round
已被替换为rounded
:
extension Double { /// Rounds the double to decimal places value func rounded(toPlaces places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } }
返回四位小数的Double示例:
let x = Double(0.123456789).roundToPlaces(4) // x becomes 0.1235 under Swift 2 let x = Double(0.123456789).rounded(toPlaces: 4) // Swift 3 version
你可以使用Swift的round
函数来实现这个目标。
要将具有3位小数精度的Double
四舍五入,首先将其乘以1000,四舍五入,然后将四舍五入的结果除以1000:
let x = 1.23556789 let y = Double(round(1000 * x) / 1000) print(y) /// 1.236
与任何类型的printf(...)
或String(format: ...)
解决方案不同,此操作的结果仍为Double
类型。
编辑:
关于有时不起作用的评论,请阅读此内容:What Every Programmer Should Know About Floating-Point Arithmetic