简体   繁体   中英

how to print specific number of digits in c++?For example ,printing 8 digits totally(before+after decimal point combined)

how to print specific number of digits in c++?For example ,printing 8 digits totally(before and after decimal point combined) Edit: For further clarification, setprecision sets the digits when i have decimal digits to display.I want to display integer 30 also as 30.000000 ,in 8 digits. The setprecision command puts fixed no. of digits after decimal and i don't want that. In short , I want an alternative of c command printf("%8d",N) in C++.

You should use the c++ header iomanip what you want is the setprecision() function:

std::cout << std::setprecision(5) << 12.3456789 << std::endl;

outputs 12.346 . It also has other modifiers you can find here
EDIT
If you want to print trailing 0s, you need to also use std::fixed . This says to use that number of digits, regardless of whether or not they are significant. If you want that to be the total number, you could figure out the size of the number, then change the precision you set it to based on that, so something like:

#include <iostream>
#include <iomanip>
#include <cmath>

int main()
{
    double input = 30;
    int magnitude = 0;

    while(input / pow(10, magnitude))
    {
        ++magnitude;
    }

    std::cout << std::fixed << std::setprecision(8 - magnitude) << input << std::endl;

    return 0;
}

This returns 30.000000 . You can also do something similar by outputting to a string, then displaying that string.

You can do it using setprecision() function from include iomanip and fixed like:

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

int main() {
    double d = 1000;
    double t = d;
    int dc=0;
    while(t>0.9)
    {
        dc++;
       t= t/10;
    }
    cout<<"dc:"<<dc<<endl;
    cout << fixed;
    std::cout << std::setprecision(dc);
    std::cout << d;
    return 0;

}

The setprecision() will not work fine every time So you have to use fixed as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM