# How to remove all decimal places?

• 05-21-2006
Rush152
How to remove all decimal places?
Can someone tell me why this code doesn't work... :confused:

Code:

#include <stdio.h>

int main(void) {

int a, i = 5.156546;

a = trunc(i);

printf("%d", a);

return(0);
}

And is there any other way to remove all numbers after a decimal place without using the trunc() function??
• 05-21-2006
cwr
Well for a start trunc takes a double and returns a double, and you're playing with ints.

Secondly, i is an int (integer), so it can't store a value of 5.156546 (not an integer).
• 05-24-2006
vangmor
int a, i = 5.156546;
i = 5 because i is integer.
try
int a;
double d = 5.156546;
a = (int) d;
or print
printf("%.0f\n", d);
• 05-27-2006
dwks
Quote:

How to remove all decimal places?
Cast to an int:
Code:

/* prints "3" */
printf("%f", (int)3.14159265358979636);

If you want to round the number, not truncuate it, use
Code:

/* prints "3" */
printf("%d", (int)(3.14159265358979636 + .5));
/* prints "4" */
printf("%d", (int)(3.6 + .5));

If you want to round the number to, say, 2 decimal places, use
Code:

/* prints "3.14" */
printf("%f", (int)(3.14159265358979636 * 100 + .5) / 100.0);

• 05-29-2006
cwr
You don't really need the convoluted arithmetic:
Quote:

Originally Posted by dwks
Cast to an int:
If you want to round the number, not truncuate it, use
Code:

/* prints "3" */
printf("%d", (int)(3.14159265358979636 + .5));
/* prints "4" */
printf("%d", (int)(3.6 + .5));

Code:

/* prints "3" */
printf("%.0f", 3.14159265);
/* prints "4" */
printf("%.0f", 3.6);

Quote:

Originally Posted by dwks
If you want to round the number to, say, 2 decimal places, use
Code:

/* prints "3.14" */
printf("%f", (int)(3.14159265358979636 * 100 + .5) / 100.0);

Code:

/* prints "3.14" */
printf("%.2f", 3.14159265358979);