gpt4 book ai didi

swift - 货币模式下小负数的 NumberFormatter 不正确行为

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:15 25 4
gpt4 key购买 nike

当使用 NumberFormatter 并将 numberStyle 设置为 .currency 时,格式化程序会按预期将所有数字四舍五入到小数点后两位。但是,对于小负数,其值四舍五入到小数点后 2 位为 0(数字 >= -0.005),输出字符串包含负号,因此变为 -$0.00 而不是 $0.00.

是否可以通过切换 NumberFormatter 的某些属性来改变这种行为,而不必使用变通方法?目前,我自己将值四舍五入到小数点后两位,检查输出是否为 -0 并采取相应措施。但是,如果 NumberFormatter 可以设置为不区分 -00,那就太好了。

下面的代码显示了问题和我当前的解决方法(随意在 Playground 上测试)- 我知道 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,如果是,则返回绝对值。

return value < -0.01 ? formatter.string(for: abs(value)) : formatter.string(for: value)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com