1、Number “1234.568”想轉(zhuǎn)成貨幣形式 “¥1,234.57”
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter
}()
}
// 打印結(jié)果SHP 1,234.57
print(Formatter.withSeparator.string(from: "1234.568")
上述得出的結(jié)果卻是 “SHP 1,234.57”
2、解決
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "zh_Hans_CN")
return formatter
}()
}
formatter對象添加設(shè)置屬性locale
formatter.locale = Locale(identifier: "zh_Hans_CN")
// 打印結(jié)果¥1,234.57
print(Formatter.withSeparator.string(from: "1234.568")
通過給對象formatter添加屬性locale實現(xiàn)想要的貨幣格式
formatter.locale = Locale(identifier: "zh_Hans_CN")
備注: 如果想要顯示成美元$符號,locale屬性設(shè)置成:en_US
formatter.locale = Locale(identifier: "en_US")