I have a currency format func that looks like this:
我有一种货币格式func,看起来是这样的:
func currencyFormat() -> NumberFormatter{
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = NumberFormatter.Style.currency
// localize to your grouping and decimal separator
currencyFormatter.locale = NSLocale.current
return currencyFormatter
}
So when I use it like this:
当我这样使用它时
currencyFormat().string(for: 20.34) --> $20.34
Same goes if I send over a negative value
同样的,如果我传递一个负值。
currencyFormat().string(for: -20.34) --> -$20.34
I don't want the negative sign to come back formatted with the currency
我不想让负面的信号被用货币格式化。
It works great but the issue I'm having is if I send it a negative decimal number, I get back the negative sign. Is there a way to drop that sign? Should I convert the decimal to positive before I send it over to the converter?
它很好,但是我的问题是如果我给它发送一个负数,我就会得到负号。有没有办法去掉这个符号?我要把小数点转换成正数再把它传送给转换器吗?
1 个解决方案
#1
1
Ensure the number is positive before sending it through the currency formatter by taking the absolute value:
在以绝对值发送货币格式化程序之前,确保数字为正数:
let number = -500
let positiveNumber = abs(number)
let formattedNumber = currencyFormat().string(for: positiveNumber)
This is the simplest and most readable way to do it.
这是最简单也是最可读的方法。
#1
1
Ensure the number is positive before sending it through the currency formatter by taking the absolute value:
在以绝对值发送货币格式化程序之前,确保数字为正数:
let number = -500
let positiveNumber = abs(number)
let formattedNumber = currencyFormat().string(for: positiveNumber)
This is the simplest and most readable way to do it.
这是最简单也是最可读的方法。