Home > Net >  String number with limited precision fraction digits in Swift
String number with limited precision fraction digits in Swift

Time:03-03

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?

CodePudding user response:

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

let decimal = Decimal(string: "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"
  • Related