-1

I am trying to round the answer to this code to 2 decimal places. I have tried a bunch of methods and none of them work for me. Please help!

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 Answers1

1

there many ways to do that

  1. if you want the value to assign it to label in string format

     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)
    

here %.2f round it to 2 decimal points and its a string value

2.you have add this extension in your project

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

then use it in ur class like

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

this will return a double value

Zeeshan Ahmad II
  • 1,047
  • 1
  • 5
  • 9