Printing the correct number of decimal points with

2019-01-01 14:37发布

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.)

标签: c++
11条回答
无色无味的生活
2楼-- · 2019-01-01 15:20

You have to set the 'float mode' to fixed.

float num = 15.839;

// this will output 15.84
std::cout << std::fixed << "num = " << std::setprecision(2) << num << std::endl;
查看更多
浪荡孟婆
3楼-- · 2019-01-01 15:21

this an example using a matrix.

cout<<setprecision(4)<<fixed<<m[i][j]
查看更多
还给你的自由
4楼-- · 2019-01-01 15:24

To set fixed 2 digits after the decimal point use these first:

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

Then print your double values.

This is an example:

#include <iostream>
using std::cout;
using std::ios;
using std::endl;

int main(int argc, char *argv[]) {
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    double d = 10.90;
    cout << d << endl;
    return 0;
}
查看更多
低头抚发
5楼-- · 2019-01-01 15:31

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
查看更多
低头抚发
6楼-- · 2019-01-01 15:32

setprecision(n) applies to the entire number, not the fractional part. You need to use the fixed-point format to make it apply to the fractional part: setiosflags(ios::fixed)

查看更多
若你有天会懂
7楼-- · 2019-01-01 15:34

I had an issue for integers while wanting consistent formatting.

A rewrite for completeness:

#include <iostream>
#include <iomanip>

int main()
{
    //    floating point formatting example

    double d = 122.345;
    cout << std::fixed << std::setprecision(2) << d << endl;
    //    Output:  122.34


    //    integer formatting example

    int i = 122;
    cout << std::fixed << std::setprecision(2) << double(i) << endl;
    //    Output:  122.00
}
查看更多
登录 后发表回答