在Swift中将负Double格式化为货币

八爪猫

我想将Double值-24.5格式化为货币格式的字符串,例如-$24.50我将如何在Swift中做到这一点?

我关注了这篇文章,但最终将其格式化为$-24.50($之后的负号),这不是我想要的。

除了类似的东西之外,还有没有更优雅的解决方案来实现这一目标?

if value < 0 {
    return String(format: "-$%.02f", -value)
} else {
    return String(format: "$%.02f", value)
}
亚历山大-恢复莫妮卡

用途NumberFormatter

import Foundation

extension Double {
    var formattedAsLocalCurrency: String {
        let currencyFormatter = NumberFormatter()
        currencyFormatter.usesGroupingSeparator = true
        currencyFormatter.numberStyle = .currency
        currencyFormatter.locale = Locale.current
        return currencyFormatter.string(from: NSNumber(value: self))!
    }
}

print(0.01.formattedAsLocalCurrency) // => $0.01
print(0.12.formattedAsLocalCurrency) // => $0.12
print(1.23.formattedAsLocalCurrency) // => $1.23
print(12.34.formattedAsLocalCurrency) // => $12.34
print(123.45.formattedAsLocalCurrency) // => $123.45
print(1234.56.formattedAsLocalCurrency) // => $1,234.56
print((-1234.56).formattedAsLocalCurrency) // => -$1,234.56

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章