【问题标题】:How to format the number in ios如何在ios中格式化数字
【发布时间】:2017-10-10 05:43:20
【问题描述】:

我想根据那里的数字基数格式化数字,比如如果我传递像 29000 这样的数字,那么数字应该转换为 29 K 如果传递的数字是 290000.. 转换后的数字应该是 2.9 M/B/ 或其他数字, 目前我正在使用以下方式

func formatNumber (number: Double) -> String? {
       let formatter = NSNumberFormatter()
       formatter.maximumFractionDigits = 1
       return formattedNumberString?.stringByReplacingOccurrencesOfString(".00", withString: "")

和使用:

let lblValue = Double(2500)/1000
lbl.text = "\(formatNumber(lblValue)!)K"

但它仅适用于给定的下标,而不适用于所有自动

【问题讨论】:

    标签: ios swift numbers


    【解决方案1】:

    请参阅 Apple 的 ByteCountFormatter

    let formatter = ByteCountFormatter()
    formatter.allowsNonnumericFormatting = false
    let byteCount = 29000
    let string = formatter.string(fromByteCount: Int64(byteCount))
    

    【讨论】:

    • 我想这个问题只涉及格式化数字而不是字节,格式化程序会将 B(yte) 附加到格式化字符串的末尾。
    【解决方案2】:

    你必须像这样手工完成:

    func format(number: Double) -> String {
    
        let sign = ((number < 0) ? "-" : "" )
        let num = fabs(number)
    
        // If its only three digit:
        if (num < 1000.0){
            return String(format:"\(sign)%g", num)
        }
    
        // Otherwise
        let exp: Int = Int(log10(num)/3.0)
        let units: [String] = ["K","M","B","T","P","E"]
    
        let roundedNum: Double = round(10 * num / pow(1000.0,Double(exp))) / 10
    
        return String(format:"\(sign)%g\(units[exp-1])", roundedNum)
    }
    
    print(format(number: 999))      // Prints 999
    print(format(number: 1000))     // Prints 1K
    print(format(number: 290000))   // Prints 290K
    print(format(number: 290200))   // Prints 290.2K
    print(format(number: 3456200))   // Prints 3.5M
    

    来源:iOS convert large numbers to smaller format

    【讨论】:

    • 这将打印print(format(3456200000)) // Prints 3.5G incase of billion。
    • 将单位数组中的 G 替换为 B。请参阅我编辑的答案
    • @SazidIqabal 很高兴听到!您能否投票或将其作为答案? :shy_face:
    猜你喜欢
    • 1970-01-01
    • 2010-09-08
    • 2017-11-16
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多