gpt4 book ai didi

swift - 在 Swift 中,舍入没有按预期发生

转载 作者:行者123 更新时间:2023-11-28 05:48:46 24 4
gpt4 key购买 nike

这是有问题的代码行:

let finalNumber = String(format: "%.2f", anotherNumber)
// where anotherNumber is a decimal like 123.456789

我得到的输出是 123.45。我预计这会四舍五入到 123.46。

谁能告诉我为什么它没有正确舍入?

最佳答案

在 playground 中尝试以下功能

func roundToDecimal(_ fractionDigits: Int, value: Double) -> Double {
let multiplier = pow(10, Double(fractionDigits))
return Darwin.round(value * multiplier) / multiplier
}


roundToDecimal(2, value: 123.456789)

你会得到你的结果 123.46

关于swift - 在 Swift 中,舍入没有按预期发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53715293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com