Search code examples
c++floating-pointiomanip

Formatting output for floating-point values just when there is fractional values in c++


I need help on how to format the output in C++ to show decimal places if there is any, or show the whole integer if there is no decimal point to show.

it should show 95.7 // When there is decimal
it should show 90   // When there is no decimal

I wrote:

cout << setprecision(1) << fixed; 

It does not give me the expected output. Instead of printing 90, it prints 90.0


Solution

  • Assuming that you are performing division.

    1. Using cout:
      i) If the decimal part turn out to be .000000, then using cout will print just the integer (the whole number) part.
      ii) If the decimal part turn out to be something other than .000000, then cout will print the decimal part as well.

      Thus, in both the cases, cout will lead to the behavior that you require.

    2. Using printf()
      i) If the decimal part turns out to be .000000, then using printf() will print the integer, followed by the decimal part, e.g., 3.000000. In this case, you will manually have to handle it so that you get the output as just 3. You can follow different approaches, like converting to a string, using inbuilt functions, etc.
      ii) If the decimal part is not .000000, then printf() will print the output like 3.123456.

    Please see the code below. I am using the fact that if the remainder of division is 0, then it means that the decimal part is .000000 and typecasting the numbers to int before printing them. You might have to use a different approach as pointed above.

    #include <iostream>
    #include <cstdio>
    using namespace std;
    
    int main() {
        double num1=270.0, num2=90.0;
        cout<<num1/num2<<"\n";                      //prints just 3
        printf("%f\n", num1/num2);                  //prints 3.000000
        if((int)num1%(int)num2==0)                  //means num1 is a multiple of num2.  So decimal is .000000
            printf("%d\n", (int)num1/(int)num2);    
    
        num2=91.0;
        cout<<num1/num2<<"\n";                      //prints 2.96703
        printf("%f\n", num1/num2);                  //prints 2.967033
        if((int)num1%(int)num2!=0)                  
            printf("%f\n", num1/num2);  
        return 0;
    }
    

    Live demo here.