将双值舍入为x小数位数有人能告诉我如何在SWIFT中把一个双值乘以x小数位数吗?我有:var totalWorkTimeInHours = (totalWorkTime/60/60)带着totalWorkTime在第二位成为NSTimeInterval(双)。totalWorkTimeInHours会给我时间,但它给了我这么长的精确数字,比如1.543240952039.当我打印的时候,我该怎么把这个算到1.543呢?totalWorkTimeInHours?
3 回答

米脂
TA贡献1836条经验 获得超3个赞
round
Double
let x = 1.23556789let y = Double(round(1000*x)/1000)print(y) // 1.236
printf(...)
String(format: ...)
Double
.
编辑:

撒科打诨
TA贡献1934条经验 获得超2个赞
SWIFT 2分机
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分机
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 }}
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

鸿蒙传说
TA贡献1865条经验 获得超7个赞
我怎样才能把这个算到,比方说,1.543呢? 当我打印totalWorkTimeInHours
?
totalWorkTimeInHours
String
format
print(String(format: "%.3f", totalWorkTimeInHours))
- 3 回答
- 0 关注
- 580 浏览
添加回答
举报
0/150
提交
取消