使用 FormatStyle API,是否可以使用“20M”或“10k”等尾随 SI 单位来格式化大数字?特别是,我正在寻找一种使用适当的本地化和货币符号来格式化大货币值(例如“$20M”)的方法。
我目前有一个货币格式化程序:
extension FormatStyle where Self == FloatingPointFormatStyle<Double>.Currency {
public static var dollars: FloatingPointFormatStyle<Double>.Currency {
.currency(code: "usd").precision(.significantDigits(2))
}
}
我想将其扩展为格式Double(20_000_000)
为“2000万美元”。
您可以创建一个自定义struct
符合FormatStyle
public struct ShortCurrency<Value>: FormatStyle, Equatable, Hashable, Codable where Value : BinaryFloatingPoint{
let locale: Locale
enum Options: Int{
case million = 2
case billion = 3
case trillion = 4
func short(locale: Locale) -> String{
switch self {
case .million:
return millionAbbr[locale, default: "M"]
case .billion:
return billionAbbr[locale, default: "B"]
case .trillion:
return trillionAbbr[locale, default: "T"]
}
}
///Add other supported locales
var millionAbbr: [Locale: String] { [Locale(identifier: "en_US") : "M"]}
var billionAbbr: [Locale: String] { [Locale(identifier: "en_US") : "B"]}
var trillionAbbr: [Locale: String] { [Locale(identifier: "en_US") : "T"]}
}
public func format(_ value: Value) -> String {
let f = NumberFormatter()
f.locale = locale
f.numberStyle = .currency
f.usesSignificantDigits = true
let basic = f.string(for: value) ?? "0"
let count = basic.count(of: ".000")
//Checks for million value
if let abbr = Options(rawValue: count)?.short(locale: f.locale){
//Get the symbol and the most significant numbers
var short = String(basic.prefix(basic.count - (4*count)))
//Append from the dictionary based on locale
short.append(abbr)
//return modified string
return short
}else{
//return the basic string
return basic
}
}
}
extension String {
func count(of string: String) -> Int {
guard !string.isEmpty else{
return 0
}
var count = 0
var searchRange: Range<String.Index>?
while let foundRange = range(of: string, options: .regularExpression, range: searchRange) {
count += 1
searchRange = Range(uncheckedBounds: (lower: foundRange.upperBound, upper: endIndex))
}
return count
}
}
然后延伸FormatStyle
@available(iOS 15.0, *)
extension FormatStyle where Self == FloatingPointFormatStyle<Double>.Currency {
public static func shortCurrency (locale: Locale? = nil) -> ShortCurrency<Double> {
return ShortCurrency(locale: locale ?? .current)
}
}
它将像任何其他产品一样可供使用FormatStyle
Text(Double(20_000_000), format: .shortCurrency())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)