iosnsnumberformatter

NSNumberFormatter different on device and simulator


I have a UITextField, using this code, print the value on the label at the bottom and formatting it.

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesGroupingSeparator:NO];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
NSNumber *calcolo = [NSNumber numberWithDouble:[value1 doubleValue]-[self.textfield.text doubleValue]];
formattedString = [formatter stringFromNumber:calcolo];
self.label.text = formattedString;

On the simulator (U.S.), the value is displayed correctly. On the device (IT), there is the comma on keyboard, but the value after the comma is always zero. enter image description here

EDIT: This works

NSNumber *temporaryValue1 = [formatter numberFromString:[NSString stringWithFormat:@"%@",value1]];
NSNumber *temporaryTextField = [formatter numberFromString:self.textField.text];
NSNumber *calcolo = [NSNumber numberWithFloat:([temporaryValue1 floatValue] - [temporaryTextField floatValue])];
formattedString = [formatter stringFromNumber:calcolo];

Solution

  • I don't think the issue is your output. The issue is the input you get from -[NSString doubleValue]. That method doesn't honor the user's locale.

    You should be able to use the formatter you made to convert self.textField.text to a number properly respecting the locale. Or you might consider using NSDecimalNumbers, especially if this is currency (looks like it?). Then NSDecimalNumber has a method +decimalNumberWithString which also does the right thing for you.