3

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];
Vins
  • 1,814
  • 4
  • 24
  • 40
  • instead of the setDecimalStyle and setting the number of diigits etc. try [numberFormatter setPositiveFormat:@"###0.##"]; – Rachel Gallen Feb 17 '13 at 13:42

1 Answers1

1

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Firoze Lafeer
  • 17,133
  • 4
  • 54
  • 48
  • @Vins This is what I said to do in my answer to your earlier question - http://stackoverflow.com/questions/14913269/ios-replace-char-in-uitextfield – rmaddy Feb 17 '13 at 16:08
  • @rmaddy yep, in fact I have listened your suggestion :) – Vins Feb 17 '13 at 17:29