• Advertisement
Sign in to follow this  

truncating floats

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a way to preform an operation that is similar to the I/O function setprecision(), except that it sets floats to a specific number or decimal places?

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by zoner7
Is there a way to preform an operation that is similar to the I/O function setprecision(), except that it sets floats to a specific number or decimal places?


Yes,


you can do:

float trunc(float number, int decplaces) {
number*=pow(10,decplaces);
number = floor (number);
number/=pow(10,decplaces);
return number;
}

you could replace floor(number) with floor(number+0.5) to get proper rounding rather than truncating.

Share this post


Link to post
Share on other sites
When and why do you want to do this? If you know in advance the accuracy requirements, and don't mind a performance hit, you can write a fixed point type instead of using floats.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement