Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ printf with %f but localized for the user's country

I'm using the following C++ syntax to output a floating point value on a Windows platform:

printf("%.2f", 1.5);

It works well if I run it on an English user account. My assumption was that if I run it on, say French user account, the output will be 1,50 instead of 1.50.

Why do I not see it and how to produce my desired result?

like image 662
ahmd0 Avatar asked Oct 07 '11 07:10

ahmd0


People also ask

What is %f in printf in C?

The f in printf stands for formatted, its used for printing with formatted output.

What is %f %S and C?

The first argument to printf is a string of identifiers. %s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

What is %U in C printf?

Explanation: In the above program, variable c is assigned the character 'a'. In the printf statement when %u is used to print the value of the char c, then the ASCII value of 'a' is printed. Case 2: Print float value using %u.


2 Answers

The radix character (i.e. '.' or ',') is defined by the current locale. The default locale (at least for Windows systems) is "C", which defines '.' as radix character.

You can set the current locale for a C/C++ program using the setlocale function.

To set the locale to the current system/user locale, you can use the following statement:

#include <locale.h>
setlocale(LC_ALL, ".OCP");

See here (cf. the examples on the linked page...) for more information about setlocale

like image 152
MartinStettner Avatar answered Sep 19 '22 15:09

MartinStettner


Try using setlocale() function http://www.cplusplus.com/reference/clibrary/clocale/setlocale/

like image 33
Damian Walczak Avatar answered Sep 20 '22 15:09

Damian Walczak