将double值舍入为x的小数位数x [英] Rounding a double value to x number of decimal places in swift

查看:126
本文介绍了将double值舍入为x的小数位数x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我如何将双重值舍入到Swift中的x个小数位数?我已经在网路上看过了,但似乎没有什么对我有用。

Can anyone tell me how to round a double value to x number of decimal places in Swift? I've looked around online, but nothing seems to be working for me.

我有:

var totalWorkTimeInHours = (totalWorkTime/60/60)

第二个NSTimeInterval(double)。 TotalWorkTimeInHours会给我几个小时,但它给了我这么长的精确数字的时间,例如1.543240952039 ......当我打印totalWorkTimeInHours的时候,怎么把这个下降到1.543?

With totalWorkTime being an NSTimeInterval (double) in second. TotalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039...... How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

提前感谢!

推荐答案

您可以使用Swift的圆形函数来完成此操作。

You can use Swift's round function to accomplish this.

要舍入一个3位数精度的 Double ,首先将其乘以1000,然后舍入,并将舍入结果除以1000:

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

除了任何一种 printf(...) String(format:...)解决方案,此操作的结果仍然是类型 Double

Other than any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double.

编辑:

关于有时无法使用的评论,请阅读以下内容:


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

每个计算机科学家应该了解浮动 - 点算术

这篇关于将double值舍入为x的小数位数x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆