views:

28

answers:

2

Hi,

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!

A: 

Since you have mentioned text field I assume the problem is in binding some numeric value to the NSTextField. The proper way here is to use NSValueFormatter, there is a customizable formatter for numerics in the IB palette. Just drop it onto the text filed and set up the rules.

Even if the task have nothing to do with UI, you can still use [NSValueTransformer valueTransformerForName:aName] to create a transformed and convert the value with it.

Gobra
I'm assuming you talk about NSNumberFormatter? I don't see how you can 'drop it onto the text field' in IB.
jv42
Correct, just drag it over the NSTextField instance, it should accept the drop.
Gobra
A: 

[string doubleValue] and a regular NSScanner always uses the . as the decimal separator. A localized NSScanner uses the decimal separator from the current locale. But both don’t know anything about grouping characters so they are inappropriate.

You have to use NSNumberFormatter to do this. Best to set it up in interface builder as @Gobra said. But you can also do this in code like this:

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle: NSNumberFormatterDecimalStyle];
double value = [[formatter numberFromString: string] doubleValue];

If you need to know wether the string was valid or not you can check if the NSNumber object returned by numberFromString: is nil before you send it the doubleValue message.

Sven