Replace comma with dot when getting floatvalue NSString

I want users to be able to enter values ​​above 0 for the amount of money in my application. Thus, 0.0 or any representation of zero would be unacceptable, but, for example, 0.1 would be accepted.

To do this, I planned to get the NSString float value and compare it to 0.0, but this will not work, since our decimal numbers should be separated by a comma, always (due to business requirements). If the commas were periods, then the comparison performs the task.

What is the most worthy way to replace commas with dots in my texts?

PS: The user is limited to enter only numbers and only one comma, for the decimal part. And actually I was wondering if this could be sthg, which could be done using formatters numbers or so ...

thanks in advance

+8
floating-point objective-c nsstring
source share
4 answers

You can just use stringByReplacingOccurrencesOfString

 NSString *newString = [ammount stringByReplacingOccurrencesOfString:@"," withString:@"."]; 
+19
source share

You can use the NSString + JavaAPI category , and then follow these steps:

 NSString* newString = [myString replace: @"," withString: @"."]; 

Of course, this may not help if the user enters something like 1,000,00 .

+4
source share

Here's a neat way to use NSScanner :

  NSScanner *scanner = [NSScanner localizedScannerWithString:theInputString]; float result; [scanner scanFloat:&result]; 
+2
source share

Apple recommends using NSScanner. this is the code i use:

 NSScanner *scanner; NSLocale *local =[NSLocale currentLocale ]; [scanner setLocale:local]; float result; scanner = [NSScanner localizedScannerWithString:<YOUR NSString>]; [scanner scanFloat:&result]; 
0
source share

All Articles