Question

I have a question - it may seem stupid to most, but i'm still a novice coder. How does one round a floating variable to display upto only 2 or 3 digits of precision ? thanks in advance

Was it helpful?

Solution

Use the format specifier %.2f for 2 digits of precision. Similarly use %.3f for 3 digits. For future reference, here are the printf format specifiers.

#include <stdio.h>

int main()
{
    printf("%.2f\n", 0.005); // prints 0.01
    printf("%.2f\n", 0.004); // prints 0.00
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top