Decimal point in calculations as . or ,

前端 未结 4 924
余生分开走
余生分开走 2021-01-23 01:48

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 contr

相关标签:
4条回答
  • 2021-01-23 02:19

    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
        }
    }
    
    0 讨论(0)
  • 2021-01-23 02:32

    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.

    0 讨论(0)
  • 2021-01-23 02:33

    You can use also the class method of NSNumberFormatter

    NSString* formattedString = [NSNumberFormatter 
                                     localizedStringFromNumber:number
                                     numberStyle:NSNumberFormatterCurrencyStyle];
    
    0 讨论(0)
  • 2021-01-23 02:42

    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.

    0 讨论(0)
提交回复
热议问题