Cpp - Output floating-point numbers

Introduction

Manipulator
Effects
showpoint

Generates a decimal point character shown in floating-point output.
The number of digits after the decimal point corresponds to the used precision.
noshowpoint

Trailing zeroes after the decimal point are not printed.
If there are no digits after the decimal point, the decimal point is not printed (by default).
fixed
Output in fixed point notation
scientific
Output in scientific notation
setprecision (int n)
Sets the precision to n.

Methods for precision

Manipulator Effects
int precision (int n); Sets the precision to n.
int precision() const; Returns the used precision.

The key word const within the prototype of precision() signifies that the method performs only read operations.

Demo

#include <iostream> 
using namespace std; 
int main() //from   w w w.ja v  a  2  s .c  o  m
{ 
    double x = 12.0; 
    cout.precision(2);                            // Precision 2 
    cout << " By default:   " << x << endl; 
    cout << " showpoint:  " << showpoint  << x << endl; 
    cout << " fixed:      " << fixed                      << x << endl; 
    cout << " scientific: " << scientific << x << endl; 
    return 0; 
}

Result

Default Standard Settings

Floating-points are displayed to six digits by default.

Decimals are separated from the integral part of the number by a decimal point.

Trailing zeroes behind the decimal point are not printed.

If there are no digits after the decimal point, the decimal point is not printed (by default).

cout << 1.0;       // Output: 1 
cout << 1.234;     // Output: 1.234 
cout << 1.234567;  // Output: 1.23457 

The last example shows that the seventh digit is rounded.

Very large and very small numbers are displayed in exponential notation.

cout << 1234567.8; // Output: 1.23457e+06 

Related Topic