How to convert a double number to 3 decimal places number in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

/**
 * Rounds a double to a specified number of decimal places.
 *
 * return the rounded number
 */
double roundTo(double n, int roundto) {
    double factor = pow(10.0, roundto);
    
    return round(n * factor) / factor;
}

int main() {
    double n = 89.560873;

    // Round to 3 decimal places
    n = roundTo(n, 3);

    printf("%.3f\n", n);

    return 0;
}

 
 
/*
run:
 
89.561
 
*/

 



answered Oct 29, 2025 by avibootz

Related questions

3 answers 315 views
1 answer 94 views
1 answer 147 views
2 answers 138 views
2 answers 159 views
2 answers 189 views
...