4

I have the following Swift code:

var yourShare: Double {
        guard let totalRent = Double(totalRent) else { return 0 }
        guard let myMonthlyIncome = Double(myMonthlyIncome) else { return 0 }
        guard let housemateMonthlyIncome = Double(housemateMonthlyIncome) else { return 0 }
        let totalIncome = Double(myMonthlyIncome + housemateMonthlyIncome)
        let percentage = Double(myMonthlyIncome / totalIncome)
        let value = Double(totalRent * percentage)

        return Double(round(100*value)/100)
    }
    

The value is then shown as a section of a form:

  Section {
               Text("Your share: £\(yourShare)")
          }

I am new to Swift and am trying to make sure that yourShare only has 2 decimal places e.g. $150.50, but at the moment it appears as $150.50000. My attempt at rounding it to 2 decimal places is the Double(round(100*value)/100) and I have also tried to use the rounded() method which did not work. The other StackOverflow articles I search suggest these 2 methods and I cannot work out what I am doing wrong here?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Jordan1993
  • 864
  • 1
  • 10
  • 28
  • Where is the code where you show the $ sign? Because that's where it should be done. Use the `NumberFormatter` (for currency). – Larme Sep 28 '20 at 09:29

2 Answers2

5

Convert it into a string with 2 digits after the decimal:

let yourShareString = String(format: "%.2f", yourShare)
3

You could do it directly inside Text with the help of string interpolation:

struct ContentView: View {
    let decimalNumber = 12.939010

    var body: some View {
        Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
    }
}
finebel
  • 2,227
  • 1
  • 9
  • 20