Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a double to fixed decimal point in C++

I have a double variable in C++ and want to print it out to the screen as a fixed decimal point number.

Basically I want to know how to write a function that takes a double and a number of decimal places and prints out the number to that number of decimal places, zero padding if necessary.

For example:

convert(1.235, 2)

would print out

1.24

and

 convert(1, 3)

would print out

1.000

so the function works as

convert(number as double, number of decimal places)

and simply prints out the required value to standard output (cout).

Does anyone know how to do this?

Thanks in advance.

like image 696
tree-hacker Avatar asked Oct 02 '10 01:10

tree-hacker


2 Answers

Assuming I'm remembering my format strings correctly,

printf("%.*f", (int)precision, (double)number);
like image 126
tc. Avatar answered Oct 13 '22 09:10

tc.


Look at the setprecision manipulator which should give you the idea

like image 31
Chubsdad Avatar answered Oct 13 '22 09:10

Chubsdad