How to avoid printing -0.000?

Sometimes in a problem we are asked to print our values correct to 3 decimal places. Simply printing 3 d.p using printf ( “%.3lf\n”, variable ) wrongly prints -0.000 sometimes. For example:

printf ( "%.3lf\n", -0.000001 );

This outputs -0.000. This then causes Wrong Answer for the problem. How do I avoid it?

This might help.

if(var <= -0.0005 || var >= 0.0005)
    printf("%.3lf\n",var);
else
    printf("0\n");
2 Likes

@sobhagya: Great. Really simple answer. I will use this from now on.