3

So I have an inner loop situation with a buffer of floating point and integer values that are to be copied over to a another buffer in string format.

What are my alternatives to round and insert a thousand separator when formatting strings? Whatever the approach I end up using, it has to be flexible enough in permitting different formats. Also, because this is a inner loop scenario, I want to optimize any solution as far as possible.

It would seem locale.h is one way to do it. But in that case, how can I setup customized locales, and how do I actually use them? Or is there a better alternative altogether? If this is a noob question please just point me in the right direction.

EDIT:

Here are a few examples to clarify:

1000 gives 1,000 (If I want to use , as thousand separator)

1000 gives 1 000 (If I want to use space as thousand separator)

1000.123 gives 1,000.1 (If I want to round to one digit and use , as thousand separator)

0 gives `` (If I want to show zero as a blank string)

I am on a POSIX system btw...

Charles
  • 50,943
  • 13
  • 104
  • 142
c00kiemonster
  • 22,241
  • 34
  • 95
  • 133

1 Answers1

3

You can try to set a locale using setlocale and use printf with the ' flag and a precision value for rounding. Whether this will work, depends on your C library.

See the following program:

#include <locale.h>
#include <stdio.h>

int main()
{
    double value = 1234567890.123;

    if (!setlocale(LC_ALL, "en_US.utf8")) {
        fprintf(stderr, "Locale not found.\n");
        return 1;
    }

    printf("%'.0f\n", value);
    printf("%'.1f\n", value);

    return 0;
}

On my Ubuntu system, the output is:

1,234,567,890
1,234,567,890.1
nwellnhof
  • 32,319
  • 7
  • 89
  • 113
  • It simply enables the thousands' separator of the current locale. – nwellnhof May 08 '13 at 14:35
  • is it possible to change the separetor? using space instead – MOHAMED May 08 '13 at 14:40
  • 1
    Not really. You could try to find a locale the uses space as thousands' separator. The French locale usually uses a space character, but it uses comma as decimal separator. If you want a portable solution, you have to write your own formatting functions. – nwellnhof May 08 '13 at 14:56