ios - 圆形功能无法按预期工作

标签 ios iphone xcode swift rounding

我正在尝试将 Double 值四舍五入到小数点后两位:

变量 x = 0.68999999999999995 var roundX = round(x * 100.0)/100.0 println(roundX)//打印 0.69

如果 print 值是正确的..但是 var 值不是我期望的,继续 0.68999999999999995

enter image description here

我需要 Double 值...而不是像其他 StackOverflow 答案那样的 String :(

最佳答案

像 double 这样的 float 没有小数位数。它们以二进制形式存储值,无法准确表示像 .69 这样的值。这只是计算机上二进制 float 的性质。

使用数字格式化程序,或按照@KRUKUSA 的建议使用 String(format:)

var x:Double = 0.68999999999999995
let stringWithTwoDecimals = String(format: "%.2f", x)
println(stringWithTwoDecimals)

关于ios - 圆形功能无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31011875/

相关文章:

ios - 如何以编程方式或从 plist 或任何其他方式本地化 iOS 应用程序的名称?

iphone - 在 iphone 中存储应用程序的数据

iOS 推送通知适用于 Dev 但不适用于 Enterprise Distribution

objective-c - 未调用 mkmapview 委托(delegate)方法 -calloutaccessorycontroltapped

iphone-sqlite 管理器

ios - UITableViewCells 向下滚动时滚动到标题

iphone - iPhone 可以安装第三方应用程序吗?如果不是的话,是如何控制的呢?

ios - 为什么我的应用程序突然无法构建并提示这些 "ld"和 "clang"错误?

ios - 如何在 Objective-C 中将 NSInteger 值转换为 int 值?

ios - 在 Xcode 中复制文件夹内容