Sign in to follow this  
makingroulette

rounding floats to X decimal places

Recommended Posts

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 this post


Link to post
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;
}

}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this