如何使用 ISOCode 在 swift 中获取带有小数点和分组分隔符的货币格式化程序
How to get the Currency formatter with decimal and grouping separator in swift using ISOCode
小数和分组分隔符不正确:
func setAmountString (amountValue: Int, isoCodeStr: String) {
let formatter = NumberFormatter()
formatter.currencyCode = isoCodeStr
formatter.numberStyle = NumberFormatter.Style.currencyISOCode
if let formatterStr: String = formatter.string(from: NSNumber(value: amountValue)) {
return formatterStr
}else {
return "0.0"
}
}
打印("amount in USD (setAmountString(amountValue: Int(1234567.89), isoCodeStr: "美元"))")
打印("amount in GBP (setAmountString(amountValue: Int(1234567.89), isoCodeStr: "GBP"))")
打印("amount in EUR (setAmountString(amountValue: Int(1234567.89), isoCodeStr: "EUR"))")
Output:
amount in USD Optional(",234,567.00")
amount in GBP Optional("£1,234,567.00")
amount in EUR Optional("€1,234,567.00")
Expected Output:
amount in USD Optional(",234,567.89")
amount in GBP Optional("£1.234.567,89")
amount in EUR Optional("€1.234.567,89")
使用locale
更改数字格式(分隔符等)使用currencyCode
更改货币符号。例如:
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currencyAccounting
formatter.locale = Locale(identifier: "DE")
formatter.currencyCode = "eur"
let string = formatter.string(from: 1234567) // "1.234.567,00 €"
错误来自您将值转换为 Int 的方式:
Int(1234567.89)
这会在将 floating-point 值传递给 setAmountString
之前将其四舍五入为 1234567
。
尝试将其转换为 Float
,或者根本不转换。您还需要更改您的函数签名
func setAmountString (amountValue: Int, isoCodeStr: String)
至
func setAmountString (amountValue: Float, isoCodeStr: String)
小数和分组分隔符不正确:
func setAmountString (amountValue: Int, isoCodeStr: String) {
let formatter = NumberFormatter()
formatter.currencyCode = isoCodeStr
formatter.numberStyle = NumberFormatter.Style.currencyISOCode
if let formatterStr: String = formatter.string(from: NSNumber(value: amountValue)) {
return formatterStr
}else {
return "0.0"
}
}
打印("amount in USD (setAmountString(amountValue: Int(1234567.89), isoCodeStr: "美元"))") 打印("amount in GBP (setAmountString(amountValue: Int(1234567.89), isoCodeStr: "GBP"))") 打印("amount in EUR (setAmountString(amountValue: Int(1234567.89), isoCodeStr: "EUR"))")
Output:
amount in USD Optional(",234,567.00")
amount in GBP Optional("£1,234,567.00")
amount in EUR Optional("€1,234,567.00")
Expected Output:
amount in USD Optional(",234,567.89")
amount in GBP Optional("£1.234.567,89")
amount in EUR Optional("€1.234.567,89")
使用locale
更改数字格式(分隔符等)使用currencyCode
更改货币符号。例如:
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currencyAccounting
formatter.locale = Locale(identifier: "DE")
formatter.currencyCode = "eur"
let string = formatter.string(from: 1234567) // "1.234.567,00 €"
错误来自您将值转换为 Int 的方式:
Int(1234567.89)
这会在将 floating-point 值传递给 setAmountString
之前将其四舍五入为 1234567
。
尝试将其转换为 Float
,或者根本不转换。您还需要更改您的函数签名
func setAmountString (amountValue: Int, isoCodeStr: String)
至
func setAmountString (amountValue: Float, isoCodeStr: String)