当使用NumberFormatter并将numberStyle设置为.currency时,格式化程序按预期将所有数字舍入到小数点后两位。但是,对于值四舍五入到小数点后2位的小负数(数字>=-0.005),输出字符串包含负号,因此变为-$0.00,而不是$0.00
有没有办法仅仅通过切换NumberFormatter的一些属性来改变这种行为,而不必使用解决方法?目前,我正在将该值舍入到小数点后两位,检查输出是否-0并相应地执行操作。不过,如果NumberFormatter可以设置为不区分-00,那就太好了。
下面的代码显示了问题和我当前的解决方法(可以在操场上自由测试)-我知道应该根据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.01,如果小于-0.01,则返回绝对值。
return value < -0.01 ? formatter.string(for: abs(value)) : formatter.string(for: value)

关于swift - 货币模式下小负数的NumberFormatter错误行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55630427/

10-13 04:11