【问题标题】:Formatting a string containing a number with comma separation格式化包含逗号分隔的数字的字符串
【发布时间】:2012-03-24 23:45:19
【问题描述】:

我有一个存储在NSMutableString 实例中的数字,我想用逗号分隔符自动格式化,然后在UITextField 中显示结果。

我尝试使用NSNumberFormatter 格式化为货币,但如果原始NSMutableString 不包含小数位,我不希望它显示小数。

例如:

  • 如果NSMutableString 包含“1234567”,则其格式应为“1,234,567”。
  • 如果NSMutableString 包含“1234567.1”,则格式应为“1,234,567.1”
  • 如果NSMutableString 包含“1234567.12”,则格式应为“1,234,567.12”

NSMutableString 将包含的最大小数为 2。

非常感谢任何帮助。

谢谢!

【问题讨论】:

    标签: iphone objective-c ios nsnumberformatter


    【解决方案1】:

    请记住,如果您正在与用户进行交互,您确实应该对此进行本地化,但是这是一种方法:

    - (NSString *)formatString:(NSString *)string {
        // Strip out the commas that may already be here:
        NSString *newString = [string stringByReplacingOccurrencesOfString:@"," withString:@""];
        if ([newString length] == 0) {
            return nil;
        }
    
        // Check for illegal characters
        NSCharacterSet *disallowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
        NSRange charRange = [newString rangeOfCharacterFromSet:disallowedCharacters];
        if ( charRange.location != NSNotFound) {
            return nil;
        }
    
        // Split the string into the integer and decimal portions
        NSArray *numberArray = [newString componentsSeparatedByString:@"."];
        if ([numberArray count] > 2) {
            // There is more than one decimal point
            return nil;
        }
    
        // Get the integer
        NSString *integer           = [numberArray objectAtIndex:0];
        NSUInteger integerDigits    = [integer length];
        if (integerDigits == 0) {
            return nil;
        }
    
        // Format the integer.
        // You can do this by first converting to a number and then back to a string,
        // but I would rather keep it as a string instead of doing the double conversion.
        // If performance is critical, I would convert this to a C string to do the formatting.
        NSMutableString *formattedString = [[NSMutableString alloc] init];
        if (integerDigits < 4) {
            [formattedString appendString:integer];
        } else {
            // integer is 4 or more digits
            NSUInteger startingDigits = integerDigits % 3;
            if (startingDigits == 0) {
                startingDigits = 3;
            }
            [formattedString setString:[integer substringToIndex:startingDigits]];
            for (NSUInteger index = startingDigits; index < integerDigits; index = index + 3) {
                [formattedString appendFormat:@",%@", [integer substringWithRange:NSMakeRange(index, 3)]];
            }
        }
    
        // Add the decimal portion if there
        if ([numberArray count] == 2) {
            [formattedString appendString:@"."];
            NSString *decimal = [numberArray objectAtIndex:1];
            if ([decimal length] > 0) {
                [formattedString appendString:decimal];
            }
        }
    
        return formattedString;
    }
    
    // Test cases:
    NSLog(@"%@", [self formatString:@"123456"]);
    NSLog(@"%@", [self formatString:@"1234567."]);
    NSLog(@"%@", [self formatString:@"12345678.1"]);
    NSLog(@"%@", [self formatString:@"123456789.12"]);
    
    // Output:
    123,456
    1,234,567.
    12,345,678.1
    123,456,789.12
    

    【讨论】:

    • 哇,谢谢!那工作得很好。我同意重新本地化,但是由于此应用程序适用于特定国家/地区,因此我采用了硬编码格式。
    【解决方案2】:

    我认为应该这样做——我添加了一个 if 语句来检查输入的值中是否有小数点。本例中的“输出”是我绑定到文本字段值以显示结果的属性。

    -(IBAction)doConversion:(id)sender{
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
        [formatter setMaximumFractionDigits:2];
        [formatter setUsesGroupingSeparator:YES];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    
        double entryFieldFloat = [entryField doubleValue]; 
        if ([entryField.stringValue rangeOfString:@"."].length == 1) {
            formatter.alwaysShowsDecimalSeparator = YES;
            self.output =[formatter stringFromNumber:[NSNumber numberWithDouble:entryFieldFloat]];
        }else{
            formatter.alwaysShowsDecimalSeparator = NO;
            self.output =[formatter stringFromNumber:[NSNumber numberWithDouble:entryFieldFloat]];
        }
    }
    

    【讨论】:

      【解决方案3】:

      调用这个方法就简单了:

      public static String GetCommaSeparatedCount(this Int32 Count)
          {
              // Check for The less-than character (<) is converted to &lt;
              String result = String.Format("{0:#,##0}", Count);
      
              return result;
          }
      

      【讨论】:

        【解决方案4】:

        您正在寻找 NSNumberFormatter 上的 -setMinimumFractionDigits: 方法。将其设置为 0,它只会显示小数点,如果有任何东西放在它后面。

        【讨论】:

        • 谢谢,我已经尝试过了,它几乎可以工作。它有几个问题让我感到困惑。当字符串包含“1234.”时,它只会显示“1234”,因此用户不会意识到他们按下的十进制键已被处理。出于某种原因,如果字符串长度为 9 个字符,则格式化程序会在格式化时更改数字。例如,如果我输入 123456789,它会格式化为“123,456,792”——知道为什么会这样吗?如果少于 9 个字符,则输入没有任何问题。
        • 这是我的代码:// Create formatter NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setMinimumFractionDigits:0]; [formatter setGroupingSeparator:@","]; entryFieldFloat = [entryField doubleValue]; NSNumber * entryFieldNumber = [NSNumber numberWithDouble:entryFieldFloat]; [enterPrice setText:[NSString stringWithFormat:@"%@", [formatter stringFromNumber:entryFieldNumber]]];
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-28
        • 2013-05-31
        • 1970-01-01
        • 2022-06-20
        • 2021-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多