2012-03-24 43 views
4

我有一個存儲在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.

任何幫助,非常感謝。

謝謝!

回答

6

請記住,你真的應該本地化這個,如果你對這個用戶進行交互,但是這裏是做這件事:

- (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:@"."] 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 
+0

哇謝謝!這工作完美。我同意重新本地化,但是因爲這個應用程序是針對特定的國家的,我已經使用硬編碼格式。 – staticnz 2012-03-25 07:48:58

0

您正在尋找有關NSNumberFormatter的-setMinimumFractionDigits:方法。將其設置爲0,如果有任何要放在它後面,它只會顯示小數點。

+0

謝謝,我試過了,它幾乎可以工作。它有幾個問題讓我困惑。 當字符串包含「1234.」時,它將只顯示「1234」,因此用戶不會意識到他們對小數點鍵的處理已經完成。 由於某些原因,如果字符串長度爲9個字符,格式化程序會在格式化時更改數字。例如,如果我輸入123456789,它的格式爲'123,456,792' - 任何想法爲什麼會發生這種情況?如果它少於9個字符,它進入沒有任何問題。 – staticnz 2012-03-25 00:27:54

+0

這是我的代碼:'//創建格式化程序 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]]];' – staticnz 2012-03-25 00:46:38

0

我想這應該做到這一點 - 我說的,如果檢查語句是否有在值輸入小數點。本例中的「輸出」是一個屬性,我已綁定到文本字段的值以顯示結果。

-(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]]; 
    } 
} 
1

只是調用這個方法很簡單:

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; 
    }