Lars -
Lars -

Reputation: 501

Decimal point in calculations as . or ,

If I use decimal pad for input of numbers the decimal changes depending of country and region format.
May be as a point "." or as a comma ","
And I do not have control over at which device the app is used.
If the region format uses a comma the calculation gets wrong. Putting in 5,6 is the the same as putting in only 5 some times and as 56 same times.
And that is even if I programmatically allow both . and , as input in a TextField.
How do I come around this without using the numbers an punctation pad and probably also have to give instructions to avoid input with comma ","
It is only input for numbers and decimal I need and the decimal pad is so much nicer.

Upvotes: 2

Views: 3579

Answers (4)

Shrikant Tanwade
Shrikant Tanwade

Reputation: 1441

Identify is local country uses comma for decimal point

var isUsesCommaForDecimal : Bool {
    let nf = NumberFormatter()
    nf.locale = Locale.current
    let numberLocalized = nf.number(from: "23,34")
    if numberLocalized != nil {
        return true
    } else {
        return false
    }
}

Upvotes: 0

vikingosegundo
vikingosegundo

Reputation: 52227

You shoudld use a NSNumberFormatter for this, as this can be set to handle different locales.

Create a formatter:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];

Use it:

NSNumber *number = [numberFormatter numberFromString: string]; //string is the textfield.text

if the device's locale is set to a locale, where the decimal separator in a ,, the Number Keypad will use is and the formatter as-well. On those the grouping separator will be .

For the other locales it will be vice-versa.

NSNumberFormatter is very sophisticated, you should read its section in Data Formatter Guide, too. It also knows a lot of currency handling (displaying, not conversion), if your app does handle such.

Upvotes: 9

gdm
gdm

Reputation: 7930

You can use also the class method of NSNumberFormatter

NSString* formattedString = [NSNumberFormatter 
                                 localizedStringFromNumber:number
                                 numberStyle:NSNumberFormatterCurrencyStyle];

Upvotes: 0

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

One way could be to check if the textField contains a ",".

If it contains, replace it with "." and do all arithmetic operations.

As anyways you will be reading all textFields and textViews as NSString object, you can manipulate the input value and transform it according to your need.

Also while showing the result replace "." with "," so that user feel comfortable according to there regional formats.

Upvotes: -2

Related Questions