iOS: formatting decimal numbers

前端 未结 2 367
小蘑菇
小蘑菇 2020-12-21 07:04

I have an NSDecimalNumber representing a money amount. I want to print it as \"999 999 999 999 999 999,00\", regardless on the locale. How do I do that?

相关标签:
2条回答
  • 2020-12-21 07:35

    Try this:

        NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"US"];
    
        NSNumberFormatter *frm = [[NSNumberFormatter alloc] init];
        [frm setNumberStyle:NSNumberFormatterDecimalStyle];
        [frm setMaximumFractionDigits:2];
        [frm setMinimumFractionDigits:2];
        [frm setLocale:usLocale];
        NSString *formattedNumberStr = [frm stringFromNumber:[NSNumber numberWithFloat:floatToRound]];
    
        [frm release];
    [usLocale release];
    
        return formattedNumberStr;
    
    0 讨论(0)
  • 2020-12-21 07:58

    I had the same problem. I was told that NSNumberFormatter converts everything to a double first. How did I solve it? It's easy, just write your own formatter.

    1. First round the decimal to 2 decimal digits.
    2. Get its description as a string.
    3. Find decimal point (.) in the string and replace it with the one you want.
    4. After every three digits from the decimal point to the left, insert a grouping separator.
    0 讨论(0)
提交回复
热议问题