0

I want to format the number according to there digit base, like if I pass the number like 29000 then the number should be converted as 29 K and if passed number is 290000.. the converted number should be 2.9 M/B/ or something else according to digit, currently im using the following way

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

and for use :

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

but it is only work for given subscript not for all and automatically

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sazid Iqabal
  • 409
  • 2
  • 21

2 Answers2

4

See Apple's ByteCountFormatter.

let formatter = ByteCountFormatter()
formatter.allowsNonnumericFormatting = false
let byteCount = 29000
let string = formatter.string(fromByteCount: Int64(byteCount))
Smartcat
  • 2,834
  • 1
  • 13
  • 25
  • I suppose the question concerns only formatting numbers not Bytes, and the formatter will append B(yte) to the end of the formatted string. – danieltmbr Oct 10 '17 at 07:29
1

You have to do it by hand like this:

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

Source: iOS convert large numbers to smaller format

danieltmbr
  • 1,022
  • 12
  • 20