How to round a float to its second or third decimal?

edited November 2015 in How To...

Hi everyone,

We have round(), ceil(), floor(), they all round float to int. Do we have functions to round float with 5 or more decimal to its second or third decimal?



  • Answer ✓

    For printing? Use nf()

    Otherwise, multiply by 100 or 1000, round and then divide again. But this might not work because it's not always possible to store decimal numbers exactly as a binary number.

  • Answer ✓

    What about modulo?

    float a = 2.34567;
    float b = a - a%0.01;
  • @koogs thanks for pointing to nf() and multiply and divide is good enough too. @benja thanks for this interesting and short solution.

Sign In or Register to comment.