首页 > 解决方案 > 如何在 Int 和 Float 类型中添加千位分隔符?

问题描述

我有一个关于添加千位分隔符的问题。
我有三种类型的数字字符串。
我在这里的堆栈中找到了答案
但我尝试使用它,并未能添加千位分隔符。
对我有什么想法吗?谢谢。

let str = "1000"
let string1 = "5000.000"
let string2 = "2000.0"

let convertStr = str.formattedWithSeparator //in playground, get error 「Value of type 'String' has no member 'formattedWithSeparator'」.
let convertStr1 = Float(string1)!.formattedWithSeparator //get error too.
let convertStr2 = Float(string2)!.formattedWithSeparator //get error too.


extension Formatter {
    static let withSeparator: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.groupingSeparator = ","
        formatter.numberStyle = .decimal
        return formatter
    }()
}

extension BinaryInteger {
    var formattedWithSeparator: String {
        return Formatter.withSeparator.string(for: self) ?? ""
    }
}

标签: iosswift

解决方案


数字格式化程序不以“数字字符串”开头;他们以数字开头。因此,例如,使用您已经拥有的 Formatter 扩展代码:

let n = 5000
let s = Formatter.withSeparator.string(for: n)
// s is now "5,000"

但是让我们说你开始的真正是一个字符串。然后你可以说,例如:

let str = "5000"
let s = Formatter.withSeparator.string(for: Float(str)!)
// s is now "5,000"

请注意,在此过程中会丢失十进制信息。如果这对您很重要,您需要将该要求添加到格式化程序本身。您正在制作一个字符串,并且您必须提供有关您希望该字符串的外观的所有信息。例如:

let str = "5000.00"
let f = Formatter.withSeparator
f.minimumFractionDigits = 2
let s = f.string(for: Float(str)!)
// s is now "5,000.00"

如果你省略了mimimumFractionDigits信息,你会"5,000"再次得到;我们开始使用的字符串的原始外观完全不重要。


推荐阅读