Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output with 3 digits after the decimal point with C++ stream?

Given a variable of float type, how to output it with 3 digits after the decimal point, using iostream in C++?

like image 754
Alex Lapchenko Avatar asked Dec 18 '11 20:12

Alex Lapchenko


People also ask

How do you print float up to 3 decimal places?

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.

How can you represent a decimal point in C?

The integer type variable is normally used to hold the whole number and float type variable to hold the real numbers with fractional parts, for example, 2.449561 or -1.0587. Precision determines the accuracy of the real numbers and is denoted by the dot (.) symbol.


2 Answers

Use setf and precision.

#include <iostream>

using namespace std;

int main () {
    double f = 3.14159;
    cout.setf(ios::fixed,ios::floatfield);
    cout.precision(3);
    cout << f << endl;
    return 0;
}

This prints 3.142

like image 57
Sergey Kalinichenko Avatar answered Sep 21 '22 01:09

Sergey Kalinichenko


This one does show "13.142"

#include <iostream>
#include <iomanip>
using namespace std;

int main(){
    double f = 13.14159;
    cout << fixed;
    cout << setprecision(3) << f << endl;
    return 0;
}
like image 26
mask8 Avatar answered Sep 18 '22 01:09

mask8