William Hu
William Hu

Reputation: 16149

NumberFormatter currency type up to 2 decimal spaces

I want to covert a String to currency and keep 2 decimal spaces:

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "zh_CN")
formatter.number(from: "¥12")        // Output 12 correct.
formatter.number(from: "¥1213.1263") // Output 1213.1263
formatter.string(from: 1213.1263)    // Output "¥1,213.13"

You can see the output in comments. Why not the formatter.number(from: "¥1213.1263") output 1213.13? I have set the max fraction digits is 2.

Upvotes: 3

Views: 1038

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

The maximumFractionDigits and all similar properties are only used for formatting the number as a string. They are not used for rounding numbers when using NumberFormatter.number(from: String).

Upvotes: 1

Related Questions