I have a need to convert NSString to double. If this string is in essence integer, then result is OK. If string is decimal, perhaps also with group separators then results are false. Any king of separator (whether “.” or “,”) whis is first in the string is always used as decimal separator.
I have tried to do something with NSScanner but I simply do not understand how to fix that problem.
Idea is following: whether I put in textfield integer, or decimal with or without group separator, I want to get proper decimal number.
I would be extremely glad to get any help.
Thanks in advance!
[string doubleValue]and a regularNSScanneralways uses the.as the decimal separator. A localizedNSScanneruses the decimal separator from the current locale. But both don’t know anything about grouping characters so they are inappropriate.You have to use
NSNumberFormatterto do this. Best to set it up in interface builder as @Gobra said. But you can also do this in code like this:If you need to know wether the string was valid or not you can check if the
NSNumberobject returned bynumberFromString:isnilbefore you send it thedoubleValuemessage.