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

What you’re looking for is truncation. This should work (at least for numbers that aren’t terribly large):

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

The conversion to integer truncates the fractional part.

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

std::trunc(100 * var) / 100     // no need for casts

Leave a Comment