rounding floats to X decimal places

Started by
4 comments, last by makingroulette 19 years, 2 months ago
Anyone know of how to do this, or a function that does it for you?
Advertisement
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.
Or, more simply: multiply by 10^X (either pow() or do a loop), floor(), divide by 10^X.

Neex proposed the übercomplex way :)

Regards,
[dead] Well, silly me!

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

I know. Not my fault. [grin]
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;
}

}

This topic is closed to new replies.

Advertisement