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
.
您可以在注释中看到输出。为什么不格式化程序。数量(来自:¥1213.1263)输出1213.13 ?我设置了最大分数位数是2。
1 个解决方案
#1
1
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)
.
最大值和所有类似的属性只用于将数字格式化为字符串。当使用NumberFormatter时,它们不用于四舍五入数字。(来自:字符串)。
#1
1
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)
.
最大值和所有类似的属性只用于将数字格式化为字符串。当使用NumberFormatter时,它们不用于四舍五入数字。(来自:字符串)。