[英]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. 我有一个UITextField,使用此代码,打印底部标签上的值并格式化它。
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 (US), the value is displayed correctly. 在模拟器(美国)上,值正确显示。 On the device (IT), there is the comma on keyboard, but the value after the comma is always zero.
在设备(IT)上,键盘上有逗号,但逗号后的值始终为零。
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];
I don't think the issue is your output. 我不认为问题是你的输出。 The issue is the input you get from
-[NSString doubleValue
]. 问题是你得到的输入
-[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. 您应该能够使用您创建的格式化程序将
self.textField.text
转换为正确尊重语言环境的数字。 Or you might consider using NSDecimalNumber
s, especially if this is currency (looks like it?). 或者您可以考虑使用
NSDecimalNumber
,特别是如果这是货币(看起来像?)。 Then NSDecimalNumber
has a method +decimalNumberWithString
which also does the right thing for you. 然后
NSDecimalNumber
有一个方法+decimalNumberWithString
,它也为你做正确的事情。
Hope that helps. 希望有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.