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

问题描述 投票:0回答:1

我想将像-24.5这样的Double值格式化为像-$24.50这样的货币格式化字符串。我怎么会在Swift中这样做?

我跟着this post,但最终格式化为$-24.50($后的负号),这不是我想要的。

有没有更优雅的解决方案来实现这一目标,除此之外?

if value < 0 {
    return String(format: "-$%.02f", -value)
} else {
    return String(format: "$%.02f", value)
}
swift string swift3
1个回答
3
投票

使用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
© www.soinside.com 2019 - 2024. All rights reserved.