Link to home
Start Free TrialLog in
Avatar of h_dineshkumar
h_dineshkumar

asked on

Controlling float precision

How to control the precision of a float variable, so that it can be used for further calculations.
Example
float a=0.1033333
printf("A= %.3f",a);  - will print A= 0.103, but
float b= a*1000 - in this statment i want A to use the value 0.103, instead of 0.103333,
so how to assign the precision to the variable, just not for printing it but also for using it later in the program.
Thanks
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You may be chasing this problem for a while. In C, you can't control the precision of a float or double variable to be different from the underlying machine representation of floating point. You can do rounding, as the sample code from ozo and zebada shows you, but on most architectures, division by powers of 10 does not give an exact result. The C libraries will provide rounding when doing formatted output of floating point, as you've already seen.

If exact control over precision is what you need, you may have to give up on using float and double data types and recode to use a fixed-precision arithmetic package. Try a search on Google for the phrase "fixed-precision arithmetic" and you'll find some starting points.
No comment has been added lately and this question is therefore classified abandoned.

If asker wishes to close the question, then refer to
https://www.experts-exchange.com/help/closing.jsp

Otherwise, I will leave a recommendation in the Cleanup topic area that this question is:
PAQed with 25:25 split between ozo and zebada

Please leave any comments here within the next seven days. It is assumed that any participant not responding to this request is no longer interested in its final disposition.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Sunny
EE Cleanup Volunteer