Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 755
Vins Avatar asked Jan 18 '26 17:01

Vins


1 Answers

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.

like image 163
Firoze Lafeer Avatar answered Jan 20 '26 10:01

Firoze Lafeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!