Decimal point in calculations as . or ,

大城市里の小女人 提交于 2019-12-02 07:11:21

问题


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.


回答1:


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.




回答2:


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.




回答3:


You can use also the class method of NSNumberFormatter

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



回答4:


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
    }
}


来源:https://stackoverflow.com/questions/15199438/decimal-point-in-calculations-as-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!