Artiom
Artiom

Reputation: 623

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?

Upvotes: 1

Views: 577

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236260

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"

Upvotes: 6

vadian
vadian

Reputation: 285039

Alternatively if you are only interested in the string regardless of any numeric modification like rounding you can strip the unwanted characters with Regular Expression

let string = "1234.5678"
let trimmedString = string.replacingOccurrences(of: "(\\d+\\.\\d{2})\\d.",
                                            with: "$1",
                                            options: .regularExpression)

Upvotes: 2

Related Questions