Home > OS >  is it possible to round the last 3 digits of a number in c?
is it possible to round the last 3 digits of a number in c?

Time:02-10

i would like to round the last 3 digits of the float number 169786.122 and leaving only 3 digits

is it possible to do it with the math.h library and the ceil function?

in case of 169786.122 == 170

in case of 169121.122 == 169

in case of 171126.122 == 171

in case of 179911.122 == 180

.. and so on

float aNum = 169726.122;

int main() {

    printf("%.0f\n",aNum); // result 169726
    return 0;
}

CodePudding user response:

#include <math.h> <-- include math.h to use the round function

To round the last 3 digit (using @Steve Summit comment as an answer)

Divide aNum by 1000, call round. (That discards 3 digits)

float aNum = 169726.122;

int main() {

    printf("%.0f\n", round(aNum / 1000)); // result 170
    return 0;
}

CodePudding user response:

If:

  • breaking ties by choosing the even multiple of 1000 is satisfactory,
  • the desired multiple of 1000 is representable in the float format, and
  • the float format uses base two or ten,

then (x - remainderf(x, 1000)) / 1000 calculates the desired result.

This works because the remainderf function always produces an exact result (has no rounding error) and, if the desired multiple of 1000 is representable, then the subtraction produces that multiple with no rounding error. If the floating-point format uses base ten, the division just changes the exponent and has no rounding error. If the format uses base two, the division of a multiple of 125 by 125 times a power of two cannot increase the number of significant bits, so the result must fit in the significand, so there is no rounding error.

These caveats are not strict; I expect various improvements are available.

  • Related