本文介绍了NSNumberFormatter numberFromString十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用 NSNumberFormatter 解析 NSString ,如下所示。

  NSNumberFormatter * myFormatter = [[[NSNumberFormatter alloc] init]; 
NSNumber * myNumber = [myFormatter numberFromString:@42.00000];

numberFromString 返回



小数点(.00000)使得模拟器中的返回值为nil,而不是在设备上。设备因为解析42(没有小数)工作正常(在模拟器和设备上)。



我使用NSNumberFormatter的原因是因为像如果字符串不是一个有效的数字(这是对我在这里:p)返回 nil 。 NSString doubleValue 不提供这种行为。此外, NSDecimalNumber decimalNumberWithString 不执行此作业,因为 [NSDecimalNumber decimalNumberWithString:@4a2 .00000] 返回4。



任何想法为什么这不会在设备上工作?



这是区域设置吗?我尝试设置 myFormatter.numberStyle = NSNumberFormatterNoStyle NSNumberFormatterDecimalStyle 但它什么也不更改。


NSNumberFormatter
的小数分隔符是
区域设置依赖。如果你有一个固定的输入格式,以点为小数分隔符
你可以设置POSIX locale:

  NSNumberFormatter * myFormatter = [[NSNumberFormatter alloc] init]; 
[myFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@en_US_POSIX]];
NSNumber * myNumber = [myFormatter numberFromString:@42.00000];

或者,您可以使用 NSScanner 双值,例如在此处描述


I'm trying to parse a NSString with a NSNumberFormatter like following.

NSNumberFormatter *myFormatter = [[[NSNumberFormatter alloc] init];
NSNumber *myNumber = [myFormatter numberFromString:@"42.00000"];

numberFromString returns a NSNumber object in the simulator but not on a device.

The decimals (.00000) are causing the return value to be nil on a device because parsing 42 (without the decimals) works just fine (both in the simulator and on a device).

The reason I'm using a NSNumberFormatter is because is like how it returns nil if the string is not a valid number (which is working against me here :p). NSString doubleValue does not provide this kind of behaviour. Also, NSDecimalNumber decimalNumberWithString doesn't do the job because [NSDecimalNumber decimalNumberWithString:@"4a2.00000"] returns 4.

Any ideas why this would not work on a device?

Is it the locale? I tried setting myFormatter.numberStyle = NSNumberFormatterNoStyle and NSNumberFormatterDecimalStyle but it changes nothing.

解决方案

As @rmaddy already said in a comment, the decimal separator of NSNumberFormatter islocale dependent. If you have a fixed input format with the dot as decimal separator,you can set the "POSIX locale":

NSNumberFormatter *myFormatter = [[NSNumberFormatter alloc] init];
[myFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSNumber *myNumber = [myFormatter numberFromString:@"42.00000"];

Alternatively, you can use NSScanner to parse a double value, as e.g. describedhere: parsing NSString to Double

这篇关于NSNumberFormatter numberFromString十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 20:24