Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

printf

I'm trying to print the number 684.545007 with 2 points precision in the sense that the number be truncated (not rounded) after 684.54.

When I use

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

it outputs 684.55, but what I'd like to get is 684.54.

Does anyone knows how can I correct this?

like image 487
vhbsouza Avatar asked Oct 05 '12 02:10

vhbsouza


2 Answers

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
like image 97
Kerrek SB Avatar answered Oct 17 '22 01:10

Kerrek SB


Here is my approach. It seems ugly but does work in most cases e.g. var can be larger then int, can be zero or bizarre '-0'. It does not handle infinities and NaNs though.

double var = 684.545007; // or whatever
double var_trunc = var>=0. ? floor(var*100.)/100. : ceil(var*100.)/100.;
printf ("%g\n", var_trunc);
like image 38
Ruslan Yushchenko Avatar answered Oct 17 '22 03:10

Ruslan Yushchenko