Alex Rivera | Logout

Formatting a (large) number "12345" to "12,345"

Asked 2009-05-06T16:42:43.530
9

Say I have a large number (integer or float) like 12345 and I want it to look like 12,345.

How would I accomplish that?

I'm trying to do this for an iPhone app, so something in Objective-C or C would be nice.

Edit
Report

2 Answers

1

I did this for an iPhone game recently. I was using the built-in LCD font, which is a monospaced font. I formatted the numbers, ignoring the commas, then stuck the commas in afterward. (The way calculators do it, where the comma is not considered a character.)

Check out the screenshots at RetroJuJu. Sorry--they aren't full-sized screenshots so you'll have to squint!

answered 2009-05-06T19:50:10.927
0

Use recursion, Luke:

#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;
}
answered 2009-05-07T11:04:28.747

Your Answer