Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setprecision in cpp for only the number of floating points

When cout-ing a number with floating points, i.e. 31.14159, how can I set cout to use the setprecision(4) on the floating point:

cout <<setprecision(4)<< 31.14159<<endl; // returns 31.14

As-is, it considers the whole number with its decimal digits, and outputs: 31.14. However, I want to get: 31.1416.

like image 940
user3639557 Avatar asked Apr 22 '15 05:04

user3639557


People also ask

How do I limit decimal places in C++?

The C++ setprecision can also be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method.

How do you display floating-point numbers in C++?

In order to force C++ to display our floating-point numbers in the scientific format regardless of the size of the number, we use the format specifier scientific inside of cout .

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

We use the %. 2f format specifier to display values rounded to 2 decimal places.


2 Answers

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

std::cout << std::setprecision(4) << std::fixed << 31.14159;

- this will print 31.1416

like image 97
Rishit Sanmukhani Avatar answered Sep 28 '22 16:09

Rishit Sanmukhani


You can use std::fixed

std::cout << std::fixed << std::setprecision(4) << 31.14159 << endl ;

and you will get output as 31.1416

When you add std::fixed, the std::setprecision(4) will take effect on the decimal part, and thus you will get 4 values after the decimal point.

A std::setprecision() will take effect on the entire number. But when you add a std::fixed along with it, the std::setprecision() will effect only the decimal part of the number.

like image 20
Arun A S Avatar answered Sep 28 '22 15:09

Arun A S