如何在swift中四舍五入?



我试图将这个代码的答案四舍五入到小数点后2位。我试过很多方法,但没有一种对我有效。请帮助!

import Foundation
var yen: Double = 10
var krona: Double = 10
var rupee: Double = 10
var totalMoney: Double
var yenRate = 0.0088
var kronaRate = 0.116
var rupeeRate = 0.013

totalMoney = yenRate*yen + kronaRate*krona + rupeeRate*rupeeRate
print("The total of all currencies is equal to (totalMoney) in USD.")

有很多方法可以做到这一点

  1. 如果您想将值以字符串格式分配给label

    var yen: Double = 10
    var krona: Double = 10
    var rupee: Double = 10
    var totalMoney: Double
    var yenRate = 0.0088
    var kronaRate = 0.116
    var rupeeRate = 0.013
    
    totalMoney = yenRate*yen + kronaRate*krona + rupeeRate*rupeeRate
    let doubleStr = String(format: "%.2f", totalMoney)
    print(doubleStr)
    

%。如果将其四舍五入到小数点后2位,则为字符串值

2。你已经在你的项目中添加了这个扩展

extension Double {
func round(to places: Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}

然后在你的类中使用它,如

totalMoney = yenRate*yen + kronaRate*krona + rupeeRate*rupeeRate
let totlaMoneyInDouble = Double(totlaMoney) 

将返回一个双精度值

相关内容

  • 没有找到相关文章

最新更新