NSNumberFormatter 与 NSNumberFormatterPercentStyle 的怪异
我需要解析 UITextField 中的一些文本并将其转换为百分比。理想情况下,我希望用户在文本字段中输入 12 或 12% 之类的内容,并将其解析为百分比数字。
这就是奇怪的地方。数字格式化程序似乎不喜欢 12,并且似乎将 12% 除以 10000 而不是 100:
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterPercentStyle];
NSNumber *n1 = [formatter numberFromString:@"12"];
NSNumber *n2 = [formatter numberFromString:@"12%"];
NSLog(@"n1 = %@", n1); // n1 = (null)
NSLog(@"n2 = %@", n2); // n2 = 0.0012
如何让格式化程序按预期返回 0.12?
编辑:这似乎只有在格式化程序首先失败时才会发生。如果格式化程序没有失败,它将按预期返回 0.12。奇怪的。
I need to parse some text in a UITextField and turn it into a percentage. Ideally, I'd like the user to either type something like 12 or 12% into the text field and have that be parsed into a number as a percentage.
Here's what's weird. The number formatter seems to not like 12 and seems to divide 12% by 10000 instead of 100:
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterPercentStyle];
NSNumber *n1 = [formatter numberFromString:@"12"];
NSNumber *n2 = [formatter numberFromString:@"12%"];
NSLog(@"n1 = %@", n1); // n1 = (null)
NSLog(@"n2 = %@", n2); // n2 = 0.0012
How do I get the formatter to return 0.12 as expected?
EDIT: it seems to only happen if the formatter fails first. If the formatter does not fail it returns 0.12 as expected. Strange.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
已知错误。
Known bug.
这是一个似乎对我有用的解决方法:
我对 NSNumberFormatter 进行子类化并实现了以下方法。似乎对我有用。
Here's a workaround that seemed to work for me:
I subclassed NSNumberFormatter and implemented the following methods. Seemed to work for me.