Controlling number of precisions

S

Sarath

Dear All,

I've a float variable with value float f = 43.125623; // some number
I need to consider only 3 digits (43.125) from the precision because
the on doing further calculations the further precision digits should
not be affected.

Converting to string with desired precesing and converting back again
to float is a solution, but is there any better way to manage this?
 
D

Dennis Jones

Sarath said:
Dear All,

I've a float variable with value float f = 43.125623; // some number
I need to consider only 3 digits (43.125) from the precision because
the on doing further calculations the further precision digits should
not be affected.

Converting to string with desired precesing and converting back again
to float is a solution, but is there any better way to manage this?

If you don't care about rounding, an easy solution is to simply multiply by
1000, cast to 'int', then divide by 1000. For example:

number = int(number * 1000)/1000.0;

If you want rounding, try this simple rounding method:

double round( double value, unsigned int decimalplaces )
{
double pow10factor = pow10(decimalplaces);
return floor(value * pow10factor + 0.5) / pow10factor;
}

- Dennis
 
G

gw7rib

Dear All,

I've a float variable with value float f = 43.125623; // some number
I need to consider only 3 digits (43.125) from the precision because
the on doing further calculations the further precision digits should
not be affected.

Converting to string with desired precesing and converting back again
to float is a solution, but is there any better way to manage this?

Do you really gain anything by doing this? Unlike a person, the
computer can probably manipulate the real number just as easily as it
can the rounded off one.

Incidentally, as humans use base ten but computers generally use
binary, it may not be storing the rounded off number accurately
anyway.

Hope that helps.
Paul.
 
K

Knockr

Do you really gain anything by doing this? Unlike a person, the
computer can probably manipulate the real number just as easily as it
can the rounded off one.

Incidentally, as humans use base ten but computers generally use
binary, it may not be storing the rounded off number accurately
anyway.

Hope that helps.
Paul.

Hello Paul,

Thanks for your reply. Actually I'm dealing with an OpenGL program
where my range of drawing is -1 to +1. So minor precision matters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top