Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show two digits after decimal point in c++ [duplicate]

Tags:

c++

precision

Similar topic is already discussed in the forum. But I have some different problem in following code:

double total; cin >> total; cout << fixed << setprecision(2) << total; 

If I give input as 100.00 then program prints just 100 but not 100.00

How can I print 100.00?

like image 681
DSKVP Avatar asked Apr 29 '13 13:04

DSKVP


People also ask

How do I print 2 digits after a decimal?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.

Can double store decimal values in C?

double takes double the memory of float (so at least 64 bits). In return, double can provide 15 decimal place from 2.3E-308 to 1.7E+308.

What is the number 2.738 correct to 2 decimal places?

74, which is 2 decimal places.

How do you show float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


2 Answers

cout << fixed << setprecision(2) << total; 

setprecision specifies the minimum precision. So

cout << setprecision (2) << 1.2;  

will print 1.2

fixed says that there will be a fixed number of decimal digits after the decimal point

cout << setprecision (2) << fixed << 1.2; 

will print 1.20

like image 77
Armen Tsirunyan Avatar answered Oct 02 '22 22:10

Armen Tsirunyan


It is possible to print a 15 decimal number in C++ using the following:

#include <iomanip> #include <iostream>  cout << fixed << setprecision(15) << " The Real_Pi is: " << real_pi << endl; cout << fixed << setprecision(15) << " My Result_Pi is: " << my_pi << endl; cout << fixed << setprecision(15) << " Processing error is: " << Error_of_Computing << endl; cout << fixed << setprecision(15) << " Processing time is: " << End_Time-Start_Time << endl; _getch();  return 0; 
like image 29
soehtetZ Avatar answered Oct 02 '22 22:10

soehtetZ