Search code examples
iosstringswiftnsnumbernsnumberformatter

Adding thousands separator "˙" to a float number


I'm working with a range of number from 0.00 to 9999.99 . I need to add the "˙" thousands separator, so 1300,00 should became 1˙300,00. NSNumberFormatter use "," as separator so it isn't good for me.

I tried using

func formatNumber (i: Float) -> String {
    var counter = 0
    var correctedNumber = ""

    if i > 999 {
        for char in "\(i)".characters {
            if counter == 1 {
                correctedNumber += "˙" + "\(char)"
            } else {
                correctedNumber += "\(char)"
            }

            counter++
        }
    } else {
        correctedNumber = "\(i)"
    }

    return correctedNumber
}

but it can't format decimal numbers.

What's the correct way to do that?


Solution

  • You just need to properly configure the NSNumberFormatter.

    let formatter = NSNumberFormatter()
    formatter.groupingSeparator = "˙"
    formatter.decimalSeparator = ","
    formatter.usesGroupingSeparator = true
    formatter.minimumFractionDigits = 2
    

    Testing

    formatter.stringFromNumber(1300) // "1˙300,00"