【问题标题】:How to add thousand separator in type Int and Float?如何在 Int 和 Float 类型中添加千位分隔符?
【发布时间】:2018-11-26 05:56:27
【问题描述】:

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

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) ?? ""
    }
}

【问题讨论】:

  • 为什么要减去我的问题?
  • 如果它解决了问题,您愿意接受答案吗?这将帮助其他人快速找出答案。

标签: ios swift


【解决方案1】:

数字格式化程序不以“数字字符串”开头;它们以数字开头。因此,例如,使用您已经拥有的 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";我们开始的字符串的原始外观完全不重要。

【讨论】:

    【解决方案2】:

    你可以用这个方法

    func currencyMaker(price: NSNumber) -> String {
    
       let numberFormatter = NumberFormatter()
       numberFormatter.numberStyle = NumberFormatter.Style.decimal
       numberFormatter.groupingSeparator = ","
       let formattedNumber = numberFormatter.string(from: price)
    
       return formattedNumber!
    }
    

    像这样:

    let myNumber1 = currencyMaker(price: 2000)
    let myNumber2 = currencyMaker(price: 5983223)
    

    打印的是:

    print(myNumber1) // 2,000
    print(myNumber2) // 5,983,223
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2023-03-30
      • 2021-11-17
      • 2012-07-12
      相关资源
      最近更新 更多