swiftstringprecisionnsnumberformatter

String number with limited precision fraction digits in Swift


What would be the fastest way to convert a String number "1234.5678" to an NSNumber with precision -> 1234.56 and back to String "1234.56".

let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = 2
numberFormatter.string(from: numberFormatter.number(from: "1234.534234")!)

This code does not look that beautiful. Any ideas?


Solution

  • You can use the new formatted method and specify the number of precision fraction length to two:

    let decimal = Decimal(
        sign: .plus,
        exponent: -4,
        significand: 12345678
    )  // 1234.5678
    decimal.formatted(.number.precision(.fractionLength(2))) // "1,234.57"
    decimal.formatted(.number.grouping(.never).precision(.fractionLength(2)))  // "1234.57"
    decimal.formatted(.number.grouping(.never).rounded(rule: .towardZero).precision(.fractionLength(2)))  // "1234.56"