我有一个数字,例如4.99999999951e + 001 我希望我可以将这个数字四舍五入为5.000000000e + 001 如何在不干扰指数部分的情况下操纵double值。
答案 0 :(得分:0)
所有double值都有一个指数部分。不要被任何打印输出工件弄糊涂,尤其是调试器的输出。
Double
具有round
和rounded
方法,您可以像这样使用它们
let value = 4.99999999951e+001
let rounded = value.rounded() // or other modes, e.g. .rounded(.toNearestOrAwayFromZero)
答案 1 :(得分:0)
您可以使用此扩展名对Double值进行四舍五入。
extension Double {
func roundTo(places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
用法:
let v = 3.56789
v.roundTo(places: 1)
我几乎在每个项目中都使用它。
答案 2 :(得分:0)
尝试使用round()
函数
var x = 3.7
x.round() output is // 4