简体   繁体   English

NSNumberFormatter故障

[英]NSNumberFormatter glitch

I have a strange problem. 我有一个奇怪的问题。 It only seems to present on a tester's iPhone 5s. 它似乎只出现在测试人员的iPhone 5s上。 It works correctly on an iPhone 5, 6 and 6 plus, all running the latest iOS (8.3). 它可以在运行最新iOS(8.3)的iPhone 5、6和6 plus上正常运行。

This is the code 这是代码

-(NSString *) commaString:(double)number
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
    [numberFormatter setGroupingSize:3];
    [numberFormatter setMaximumSignificantDigits:9];
    NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble: number]];

    return numberAsString;
}

The application is a calculator and is usually presenting correctly like this 该应用程序是一个计算器,通常像这样正确显示

It is usually showing correctly like this 通常这样正确显示 在此处输入图片说明
but on this iPhone 5s it is showing like this 但在这部iPhone 5s上却像这样显示 在此处输入图片说明

I thought the setMaximumSignificantDigits would have nipped this in the bud, but it's still showing the same. 我以为setMaximumSignificantDigits可以将其扼杀在萌芽状态,但它仍显示相同的内容。 Could this be some strange localisation thing? 这可能是一些奇怪的本地化问题吗? I don't think it is as his iPhone 6 it is showing correctly also. 我不认为这是因为他的iPhone 6也能正确显示。
Thanks 谢谢
Luke 卢克

If your goal is to simply have commas every three characters, all you need to do is: 如果您的目标是仅使每三个字符使用逗号,那么您要做的就是:

    NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;

    NSNumber * numberFromString = [numberFormatter numberFromString:currentTextWithoutCommas];
    NSString * formattedNumberString = [numberFormatter stringFromNumber:numberFromString];

If you're finding that there's an issue with localizing the formatter, then set secondaryGroupingSize to 3. As written in the docs for NSNumberFormatter : 如果发现格式化程序本地化存在问题,则将secondaryGroupingSize设置为3。如在NSNumberFormatter文档中所写:

Some locales allow the specification of another grouping size for larger numbers. 一些语言环境允许为更大的数字指定另一个分组大小。 For example, some locales may represent a number such as 61, 242, 378.46 (as in the United States) as 6,12,42,378.46. 例如,某些语言环境可能表示61、242、378.46(例如在美国)为6,12,42,378.46。 In this case, the secondary grouping size (covering the groups of digits furthest from the decimal point) is 2. 在这种情况下,辅助分组大小(覆盖距离小数点最远的数字组)为2。

Also, you can check out Formatting Numbers on iOSDeveloperTips for a brief, high-level overview. 另外,您可以在iOSDeveloperTips上查看格式化数字 ,以获取简要的高级概述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM