Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

decimal

printf

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!

like image 272
Javi Ortiz Avatar asked Feb 07 '13 14:02

Javi Ortiz


People also ask

Can comma be used instead of decimal point?

Both a comma and a period (or full-stop) are generally accepted decimal separators for international use.

Why are my decimal points commas?

Your Regional Settings in your Control Panel on your device are used by default by Excel to determine if decimals should be a period or dot (used in the US and in English Canada for example) or if decimals are a comma (used in many European countries and French Canada).

How do you use a dot as separator?

If you want to use the dot or decimal point as separator you need to switch the language for the corresponding cells to English: Select the corresponding cells (press CTRL + A to select all cells of a sheet) Select Format → Cells from the menu.

Why do Germans use comma instead of decimal point?

In German the comma rather than the period is used as a decimal separator and the dot is used as a thousands separator: 12.345,67 . The comma creates some unwanted space when used as in $12.345,67$ .


2 Answers

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;
}
like image 173
Nemanja Boric Avatar answered Oct 06 '22 23:10

Nemanja Boric


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.

like image 36
Ivaylo Strandjev Avatar answered Oct 07 '22 00:10

Ivaylo Strandjev