printf question

shanker

Well-known member
Joined
Sep 18, 2016
Messages
291
Reaction score
16
Location
Romania
E:G:

float S;
int N = 5;
S = (float) N / 2;
std::cout << S;

It will output to 2.5

if N was 6, then the output was 3.

So, how can i do the same as below with printf? If the number is an integer, how to remove the .00?

float S;
int N = 5;
S = (float) N / 2;
printf("%0.2f", S);

It will output to 2.50. If N was 3 then the output was 3.00. I want to remove .00 when is the case to.
 

monday

Expert
Joined
Jun 23, 2014
Messages
1,127
Solutions
1
Reaction score
158
If you don't find any better solution you can do something like:

Code:
#include <stdio.h>

void Pretty_float_print(float f){
    if ((int)f == f){
        printf("%.0f", f);
    } else{
        printf("%.2f", f);
    }
}

int main()
{
    float float_num = 1.5;
    
    Pretty_float_print(float_num);
    return 0;
}
 

monday

Expert
Joined
Jun 23, 2014
Messages
1,127
Solutions
1
Reaction score
158
This "Pretty_float_print" is not really useful if you have printf function with many params...
Printf allows to supply the precision number as an additional parameter if instead of providing precision digit you supply "*" character. You can use ternary operator to do something like this:



Code:
#include <stdio.h>

int main()
{
    float f = 1.5;
   
    printf("%.*f", f == (int)f ? 0 : 2, f);

    return 0;
}

In this case printf is supplied with 3 arguments:
format string,
number of precision of the float (it's 0 if float is a whole number and 2 if it isn't)
float f
 

y0mike

Active member
Joined
May 10, 2014
Messages
97
Reaction score
41
Location
mizus girl's house
Yes.

You can check if it is a whole number this way
Code:
float f = 0.5f;
if (floor(f) == f)
{
    printf("%d", static_cast< int >( f ) );
}
else
{
    printf("%.2f", f);
}

or simpler

Code:
float f = 0.5f;
bool whole = floor(f) == f;
printf( whole ? "%d" : "%.2f", whole ? static_cast< int >( f ) : f );
 
Top