Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the correct number of decimal points with cout

Tags:

c++

I have a list of float values and I want to print them with cout with 2 decimal places.

For example:

10.900  should be printed as 10.90 1.000 should be printed as 1.00 122.345 should be printed as 122.34 

How can I do this?

( setprecision doesn't seem to help in this.)

like image 952
thameera Avatar asked May 06 '11 05:05

thameera


People also ask

How do you correct decimal places in C++?

By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.

How do I get 2 decimal places in C++?

We use the printf() in C++ to display strings in the desired format. It is a part of the cstdio header file. We use the %. 2f format specifier to display values rounded to 2 decimal places.

How do you find the correct number of decimal places?

For the number of decimal places stated, count that number of digits to the right of the decimal and underline it. The next number to its right is called the 'rounder decider'. If the 'rounder decider' is 5 or more, then round the previous digit up by 1.


2 Answers

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream> #include <iomanip>  int main() {     double d = 122.345;      std::cout << std::fixed;     std::cout << std::setprecision(2);     std::cout << d; } 

And you will get output

122.34 
like image 101
beduin Avatar answered Oct 03 '22 23:10

beduin


You were nearly there, need to use std::fixed as well, refer http://www.cplusplus.com/reference/iostream/manipulators/fixed/

#include <iostream> #include <iomanip>  int main(int argc, char** argv) {     float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };      std::cout << std::setprecision(2) << std::fixed;      for(int i = 0; i < 6; ++i)     {         std::cout << testme[i] << std::endl;     }      return 0; } 

outputs:

0.12 1.23 12.35 123.45 1234.50 12345.00 
like image 34
Vusak Avatar answered Oct 03 '22 22:10

Vusak