Search code examples
iosswiftdoublerounding

Rounding a double value (1.005) to (1.01)


Problem with rounding the number 1.005 in swift

rounding 1.005 to two decimal places results in 1.0 instead of 1.01 how to solve it?

for i in 1..<11 {
    let value = Double(i) + 0.005
    let roundedValue = round(value * 100) / 100.0
    print(value, roundedValue)
}

Output:

1.005  -> 1.0
2.005  -> 2.01
3.005  -> 3.01
4.005  -> 4.01
5.005  -> 5.01
6.005  -> 6.01
7.005  -> 7.01
8.005  -> 8.01
9.005  -> 9.01
10.005  -> 10.01

Solution

  • Just use a NumberFormatter and set the roundingMode to halfUp:

    extension Formatter {
        static let number: NumberFormatter = {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            formatter.minimumFractionDigits = 2
            formatter.maximumFractionDigits = 2
            formatter.roundingMode = .halfUp
            return formatter
        }()
    }
    

    Formatter.number.string(for: 1.005)   // "1.01"
    Formatter.number.string(for: 2.005)   // "1.01"
    Formatter.number.string(for: 3.005)   // "1.01"
    Formatter.number.string(for: 4.005)   // "1.01"
    Formatter.number.string(for: 5.005)   // "1.01"
    Formatter.number.string(for: 6.005)   // "1.01"
    Formatter.number.string(for: 7.005)   // "1.01"
    Formatter.number.string(for: 8.005)   // "1.01"
    Formatter.number.string(for: 9.005)   // "1.01"
    Formatter.number.string(for: 10.005)  // "1.01"