# rounding floats to X decimal places

This topic is 4908 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Anyone know of how to do this, or a function that does it for you?

##### Share on other sites
Hi,

I can think of one way of doing it, but I doubt it would be very fast.

1) Remove all digits before the decimal point by converting the float to an int, then taking that int away from the float again.

2) Multiply by 10, convert to an int, and you have the 1st decimal place. Repeat 1) then multiply by 10 and convert to an int, and you have the 2nd decimal place, and so on...

That's a lot of float->int conversions, so I hope you don't want to do this thousands of times a frame!

I've not tried it, but I think it should work. Note that it will truncate the last digit, rather than rounding it properly.

##### Share on other sites
Or, more simply: multiply by 10^X (either pow() or do a loop), floor(), divide by 10^X.

Neex proposed the übercomplex way :)

Regards,

##### Share on other sites

PS, Emmanuel your rating is 1337.

##### Share on other sites
Quote:
 Original post by Neex[dead] Well, silly me!PS, Emmanuel your rating is 1337.

I know. Not my fault. [grin]

##### Share on other sites
based on what you told me i developed a function for rounding

// number is the number that you want to round to X number of decimal places
// places is the number of places that you want to round 'number' to

Round(3.145,2) would produce output of 3.15 as expected

float Round(float number, int places)
{
int n = number * pow(10, (places + 1));

int remainder = n%10;

if( remainder > 4)
{
float result = ((n - remainder) + 10)/pow(10,(places+1));

return result;
}

if( remainder < 5)
{
float result = (n - remainder)/pow(10,(places+1));
return result;
}

}

1. 1
2. 2
Rutin
23
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 23
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631766
• Total Posts
3002233
×