[英]What is wrong with this string format (different behavior on simulator and device)?
我按下一个数字时执行了这段代码:
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]);
现在如果我在模拟器中运行它并按3我得到以下结果:
1: 0.03
2: 0.03
如果我在设备上运行它,我有:
1: 0.03
2: 0
所以基本上在设备上格式化的数字是0。
我还注意到,在模拟器上,我得到了' 。 '作为小数分隔符,在我有' , '的设备上。
因此,它永远不会进一步发展。 按下它的任何数字仍为0。
什么似乎是问题?
您的设备显然是设置为使用欧洲(或地方)区域,
作为小数点分隔符。 尝试在您alloc
行之后添加此行并init
您的数字格式化程序:
[f setDecimalSeparator:@"."];
或者使用setLocale
方法(或更改设备设置的语言环境)。
试试这样:
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.