将一个(较大的)数字“12345”格式化为“12,345”。

9

假设我有一个大量的数字(整数或者小数),例如12345,我希望它显示为12,345

我该怎么做呢?

我正在尝试在iPhone应用中实现这个功能,所以使用Objective-C或C语言会很不错。


这里也有一些不错的答案:如何在Objective C中每3位数字添加逗号? - JohnK
7个回答

31

这里是答案。

  NSNumber* number = [NSNumber numberWithDouble:10000000];
  NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
  [numberFormatter setNumberStyle:kCFNumberFormatterDecimalStyle];
  [numberFormatter setGroupingSeparator:@","];
  NSString* commaString = [numberFormatter stringForObjectValue:number];
  [numberFormatter release];
  NSLog(@"%@ -> %@", number, commaString);

1
一个小更新:最好使用NSNumberFormatterDecimalStyle而不是kCFNumberFormatterDecimalStyle(在XCode 5上进行显式枚举比较会显示警告)。 - Guy Chen

17

尝试使用NSNumberFormatter

这将允许您在iPhone上正确处理此内容。但请确保使用10.4以上的样式。来自该页面的信息:

"iPhone OS: 在iPhone OS上,v10.0兼容模式不可用,仅可用10.4模式。"


谢谢!我怎么会错过那个呢。 :) - Kriem

3
在Mac OS X上,您可以在printf(3)中使用“'”字符串格式化器。 $ man 3 printf
     `''          Decimal conversions (d, u, or i) or the integral portion
                  of a floating point conversion (f or F) should be
                  grouped and separated by thousands using the non-mone-
                  tary separator returned by localeconv(3).

例如在 printf("%'6d",1000000) 中;


2

更干净的C代码

// write integer value in ASCII into buf of size bufSize, inserting commas at tousands
// character string in buf is terminated by 0.
// return length of character string or bufSize+1 if buf is too small.
size_t int2str( char *buf, size_t bufSize, int val )
{
    char *p;
    size_t len, neg;

    // handle easy case of value 0 first
    if( val == 0 )
    {
         a[0] = '0';
         a[1] = '\0';
         return 1;
    }


    // extract sign of value and set val to absolute value
    if( val < 0 )
    {
        val = -val;
        neg = 1;
    }
    else
        neg = 0;

    // initialize encoding
    p = buf + bufSize;
    *--p = '\0';
    len = 1;

    // while the buffer is not yet full
    while( len < bufSize )
    {
         // put front next digit
         *--p = '0' + val % 10;
         val /= 10;
         ++len;

         // if the value has become 0 we are done
         if( val == 0 )
             break;

         // increment length and if it's a multiple of 3 put front a comma
         if( (len % 3) == 0 )
             *--p = ',';
   }

   // if buffer is too small return bufSize +1 
   if( len == bufSize && (val > 0 || neg == 1) )
       return bufSize + 1;

   // add negative sign if required
   if( neg == 1 )
   {
       *--p = '-';
       ++len;
   }

   // move string to front of buffer if required
   if( p != buf )
       while( *buf++ = *p++ );

   // return encoded string length not including \0
   return len-1;
}

1
我最近为一个iPhone游戏做了这个。我使用了内置的LCD字体,这是一种等宽字体。我格式化了数字,忽略了逗号,然后再把逗号插入进去。(计算器的方式,逗号不被视为字符。)
请查看RetroJuJu上的屏幕截图。抱歉-它们不是全尺寸的屏幕截图,所以您需要眯起眼睛!

0
希望这能对你有所帮助(它是用C语言编写的):
char* intToFormat(int a)
{
    int nb = 0;
    int i = 1;
    char* res;

    res = (char*)malloc(12*sizeof(char));
    // Should be enough to get you in the billions. Get it higher if you need
    // to use bigger numbers.

    while(a > 0)
    {
        if( nb > 3 && nb%3 == 0)
            res[nb++] = ',';

        // Get the code for the '0' char and add it the position of the
        // number to add (ex: '0' + 5 = '5')
        res[nb] = '0' + a%10;

        nb++;
        a /= 10;
    }

    reverse(&res);
    return res;
}

可能有一些我没有看到的错误(在这方面我是盲人...) 它就像一个增强版的iToA,所以也许不是最好的解决方案。


0

使用递归,卢克:

#include <stdio.h>
#include <stdlib.h>

static int sprint64u( char* buffer, unsigned __int64 x) {
  unsigned __int64 quot = x / 1000;
  int chars_written;
  if ( quot != 0) {
    chars_written = sprint64u( buffer, quot);
    chars_written += sprintf( buffer + chars_written, ".%03u", ( unsigned int)( x % 1000));
  }
  else {
    chars_written = sprintf( buffer, "%u", ( unsigned int)( x % 1000));
  }
  return chars_written;
}
int main( void) {
  char buffer[ 32];
  sprint64u( buffer, 0x100000000ULL);
  puts( buffer);
  return EXIT_SUCCESS;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接