[英]What is wrong with this string format (different behavior on simulator and device)?
I have this block of code executed when pressing a number: 我按下一个数字时执行了这段代码:
NSString *currentValue = [@"" stringByAppendingFormat:@"%.02f", [[[[[textField text] stringByReplacingOccurrencesOfString:@"." withString:@""] stringByReplacingOccurrencesOfString:@"," withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] doubleValue]/100.0f];
//I am using this to obtain always a number with 2 decimals.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMinimumFractionDigits:2];
[f setMaximumFractionDigits:2];
[f setGroupingSeparator:@" "];
NSNumber *currentNumberValue = [f numberFromString:currentValue];
NSLog(@"1: %@", currentValue);
NSLog(@"2: %@", [currentNumberValue stringValue]);
Now if I run this in the simulator and press 3 I get the following results: 现在如果我在模拟器中运行它并按3我得到以下结果:
1: 0.03
2: 0.03
If I run it on the device I have: 如果我在设备上运行它,我有:
1: 0.03
2: 0
So basically on the device the formated number is 0. 所以基本上在设备上格式化的数字是0。
What I have also noticed is that on the simulator I get ' . 我还注意到,在模拟器上,我得到了' 。 ' as a decimal separator and on the device I have ' , '.
'作为小数分隔符,在我有' , '的设备上。
And because of this it never gets further. 因此,它永远不会进一步发展。 Any number I press it still remains 0.
按下它的任何数字仍为0。
What seems to be the problem? 什么似乎是问题?
Your device is apparently set to a European (or wherever) locale that uses ,
as the decimal separator. 您的设备显然是设置为使用欧洲(或地方)区域
,
作为小数点分隔符。 Try adding this line after the line where you alloc
and init
your number formatter: 尝试在您
alloc
行之后添加此行并init
您的数字格式化程序:
[f setDecimalSeparator:@"."];
Or use the setLocale
method (or change the locale your device is set to). 或者使用
setLocale
方法(或更改设备设置的语言环境)。
Try it like this: 试试这样:
NSString *currentValue = [textField text];
float currentFloat = [currentValue floatValue];
NSLog(@"%.2f",currentFloat); //string representation of floatValue
NSLog(@"%@",currentValue); //string currentValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.