Search code examples
swiftnumber-formatting

Rounding a double to 2 decimal places in Swift, XCode 12


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?


Solution

  • 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
        }
    }