使用NumberFormatter
并将numberStyle
设置为.currency
时,格式化程序将所有数字四舍五入到小数点后两位。但是,对于较小的负数(其值四舍五入到小数点后两位)(数字> = -0.005),输出字符串包含负号,因此变为-$0.00
而不是$0.00
。
是否存在仅通过切换NumberFormatter
的某些属性而不必使用替代方法来更改此行为的方法?目前,我自己将值四舍五入到小数点后两位,检查输出是否为-0
并采取相应措施。但是,最好将NumberFormatter
设置为不区分-0
和0
。
下面的代码显示了问题和我当前的解决方法(可以在操场上进行测试)-我知道Locale
应该基于currencySymbol
进行设置,但这只是展示代码问题,而不是生产代码):
public class CurrencyFormatter {
private let formatter: NumberFormatter
public init(locale: Locale = Locale.current) {
let formatter = NumberFormatter()
formatter.locale = locale
formatter.numberStyle = .currency
self.formatter = formatter
}
// Adds currency symbol and returns a string e.g. input 1 output "£1"
public func formatWithCurrencySymbol(value: Decimal, currencyCode: String) -> String? {
formatter.currencyCode = currencyCode
// Workaround for cases when the currency behaviour rounds small negative values (<0.0051) to -0.00, where we don't want to have a - sign
var value = value
if value < 0 {
let roundedValue = round(Double(truncating: value as NSDecimalNumber) * 100.0)
if roundedValue == 0 && roundedValue.sign == .minus {
value = 0
}
}
return formatter.string(for: value)
}
public func formatWithCurrencySymbolNoWorkaround(value: Decimal, currencyCode: String) -> String? {
formatter.currencyCode = currencyCode
return formatter.string(for: value)
}
}
let formatter = CurrencyFormatter()
formatter.formatWithCurrencySymbol(value: 0.01, currencyCode: "USD") // "$0.01"
formatter.formatWithCurrencySymbol(value: -0.001, currencyCode: "EUR") // "€0.00"
formatter.formatWithCurrencySymbol(value: -0.0002, currencyCode: "EUR") // "€0.00"
formatter.formatWithCurrencySymbol(value: -0.01, currencyCode: "EUR") // "-€0.01"
formatter.formatWithCurrencySymbol(value: 0.01, currencyCode: "USD") // "$0.01"
formatter.formatWithCurrencySymbol(value: -0.001, currencyCode: "EUR") // "-€0.00"
formatter.formatWithCurrencySymbol(value: -0.0002, currencyCode: "EUR") // "-€0.00"
formatter.formatWithCurrencySymbol(value: -0.01, currencyCode: "EUR") // "-€0.01"
formatter.formatWithCurrencySymbolNoWorkaround(value: -0.005, currencyCode: "EUR") // "-€0.00"
答案 0 :(得分:0)
您可以添加简单的逻辑来检查该值是否小于-0.01,如果是,则返回绝对值。
return value < -0.01 ? formatter.string(for: abs(value)) : formatter.string(for: value)