C/C++: printf use commas instead of dots as decimal separator

21,593

Solution 1

If you want, you can set current locale at the beginning of your program:

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


int main()
{
    setlocale(LC_NUMERIC, "French_Canada.1252"); // ".OCP" if you want to use system settings
    printf("%f\n", 3.14543);
    return 0;
}

Solution 2

There is no similar functionality in C. You can use sprintf to print into a char array and then replace the dot with a comma manually. I can't think of a better solution, sorry.

EDIT: thanks to Mats Patersson's comment: It seems setting the locale can change this character. Please have a look at the link he posted.

Share:
21,593
Javi Ortiz
Author by

Javi Ortiz

Updated on February 08, 2020

Comments

  • Javi Ortiz
    Javi Ortiz over 4 years

    I need that my program shows the output using commas as decimal separator.

    According to this link: http://www.java2s.com/Code/Java/Development-Class/Floatingpointwithcommasf.htm you can use in Java something like this:

    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
    

    Is there a flag or something that I can use to have a similar behaviour in C?

    Thanks in advance!

  • James Black
    James Black over 11 years
    +1 - I think your answer was better than mine, as locale may be the correct fix.
  • Lundin
    Lundin over 7 years
    Similarly, const struct lconv* loc = localeconv(); can be used to get locale specifics. From there you can check loc->decimal_point[0] to see which decimal separator that is currently used.
  • elephant
    elephant over 6 years
    also you may get current locale with setlocale(LC_ALL, NULL); to restore it afterwards.