Show five digits after decimal point in c++ but if there are 0 after decimal point don't print them

2.5k views Asked by At

The number must be displayed with exactly five digits after the decimal. If the number is 0 to display only 0 instead of 0.00000. If the number has zeros in his decimal recording only show numbers other than zero, for example 0.08500 instead of outputting 0.085 //s0 is my variable

if (s0==) cout<<"0"
else cout<<setiosflags(ios::fixed)<<setprecision(5)<<s0;
4

There are 4 answers

1
paweldac On

Try:

std::cout << std::setprecision(5) << s0;

In your version setiosflags(ios::fixed) is forcing trailing zeros.

0
Malcolm McLean On

You can't easily do it in C++ with the streams and << operator, because 0 is a special case.

Write a function

 std::string tonice(double x)
 {
    char buff[64];
    if(x == 0)
       sprintf(Buff, "0");
    else
       sprintf(buff, "%5.3f", x);
    return std;string(buff);

  }

Then

 cout << "The data is " << tonice(x) << " other bits and bats";
0
mohor chatt On

std::cout << std::setprecision(5) << s0; This is the best method for setting precision.

1
Pedro Lobo On

It seems obvious, but could you use printf?

#include <stdio.h>

int main(){

    printf("%5.3f", 0.8500000000);
    return 0;
}