【问题标题】:Converting String to Double in Swift reveals extra decimal places [duplicate]在 Swift 中将 String 转换为 Double 会显示额外的小数位 [重复]
【发布时间】:2020-03-15 23:41:01
【问题描述】:

我正在尝试通过将输入数字转换为字符串然后再转换为双精度数来将数字舍入到小数点后 7 位。字符串的值是我想要的,但是当将其转换回双精度时,会显示更多小数位。这种情况有什么补救措施吗?

let inputNumber: Double = 99.99990338164251

let roundedString = String(format: "%.7f", inputNumber) //"99.9999034"

let outputNumber = Double(roundedString) //99.99990339999999

【问题讨论】:

  • 在向用户显示浮点数时可以使用 NSNumberFormatter。如果您需要更高的精度,可以使用 Swift Decimal 类型

标签: swift string format double rounding


【解决方案1】:

使用Decimal 类而不是Double https://developer.apple.com/documentation/foundation/decimal

你的问题是浮点数计算的常见问题

更多关于 ObjC 类https://developer.apple.com/documentation/foundation/nsdecimalnumber

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2020-06-22
    • 2013-11-10
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多