2017-10-10 114 views
0

我想根據數字格式對數字進行格式化,例如,如果我通過數字如29000,那麼數字應該轉換爲29 K ,如果通過數字是290000 ..轉換數量應該是2.9 M/B /或根據數字別的東西, 目前即時通訊使用以下方式如何在ios中格式化數字

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" 

但它只是爲給定的工作標不全部自動

回答

4

請參閱Apple的ByteCountFormatter

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

我想,這個問題僅涉及格式化數字不是字節,而且該格式將追加B(YTE)到格式化的字符串的末尾。 – danieltmbr

0

你必須手工完成這樣的:

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

+0

謝謝,讓我檢查一下,它是否有效 –

+1

這將打印'print(format(3456200000))//打印3.5G'數十億。 –

+0

用單位數組中的B替換G.請參閱我編輯的答案 – danieltmbr