Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
Matte.Car Avatar asked Dec 27 '15 13:12

Matte.Car


2 Answers

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"
like image 140
Luca Angeletti Avatar answered Nov 14 '22 21:11

Luca Angeletti


While setting a specific decimalSeparator and groupingSeparator certainly works, it's not the best way to do what you want.

NSNumberFormatter always chooses the format according to the current locale. If the locale is set to English (usually en-US), then decimal separator will be a , and grouping separator a ..

This way if a user in USA opens the app, they will see number formatted correctly for them. If a user in Europe opens the app, they will also see numbers formatted correctly (as specified by their device settings).

If you really want the app to have one specific number format, you can just set the language explicitly, e.g:

let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "it_IT")
like image 45
Sulthan Avatar answered Nov 14 '22 21:11

Sulthan