How to truncate a floating point number after a certain number of decimal places (without rounding)?

I am trying to print the number 684.545007 with an accuracy of 2 points in the sense that after 684.54 number will be truncated (not rounded).

When i use

 var = 684.545007; printf("%.2f\n",var); 

outputs 684.55 , but I would like to get 684.54 .

Does anyone know how I can fix this?

+8
c ++ c printf
source share
3 answers

What you are looking for is truncation. This should work (at least for numbers that are not very large):

 printf(".2f", ((int)(100 * var)) / 100.0); 

Converting to an integer truncates the fractional part.

In C ++ 11 or C99, you can use the dedicated trunc function (from the <cmath> or <math.h> header) for this purpose. will avoid restrictions on values ​​that fit into the integral type.

 std::trunc(100 * var) / 100 // no need for casts 
+22
source share

Here is my approach. It seems ugly, but works in most cases, for example. var may be greater than int, may be null or fancy '-0'. However, it does not handle infinity and NaNs.

 double var = 684.545007; // or whatever double var_trunc = var>=0. ? floor(var*100.)/100. : ceil(var*100.)/100.; printf ("%g\n", var_trunc); 
+2
source share
 printf("%.2f\n", var - 0.005); 
+1
source share

All Articles