![](templates/subSilver/images/CCSLogo.jpg) |
![CCS C Software and Maintenance Offers](templates/subSilver/images/forumAd6.jpg) |
View previous topic :: View next topic |
Author |
Message |
trustno1
Joined: 25 Nov 2007 Posts: 4
|
float variable with only 2 decimal |
Posted: Sun Jan 06, 2008 9:56 am |
|
|
Hi.
i need to know how truncate a float VARIABLE, for example:
1,23456 ----> 1,23
couse i have to compare values with only two decimal numbers.
Thanks. |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah Guest
|
|
Posted: Sun Jan 06, 2008 10:20 am |
|
|
Do you absolutely 'have' to be working with float values?. If not, consider using the %w print format, and working using 16bit, or 32bit scaled integers, so you hold 1.23xxx, as 123. Will make comparisons much more accurate, and faster.
If you must use float values, you start to run into the problems that the 'edges' for a trimmed value, will not be well defined, depending on the size of the value concerned. If you want 4/5 rounding, then using a cast is probably the best solution, so:
Code: |
if ((int32)(val*100 +0.49999) == 123)
|
Which will take the float value, multiply it by 100,add 0.49999 (so that 1.236xxx will become 124xxxx), and tun it into an integer for the comparison.
The internal ceil, and floor functions, can also be used on the value*100, but the comparison will be less accurate, and slower.
Best Wishes |
|
![](templates/subSilver/images/spacer.gif) |
trustno1
Joined: 25 Nov 2007 Posts: 4
|
|
Posted: Sun Jan 06, 2008 1:59 pm |
|
|
Ttelmah wrote: |
If you must use float values, you start to run into the problems that the 'edges' for a trimmed value, will not be well defined, depending on the size of the value concerned. If you want 4/5 rounding, then using a cast is probably the best solution, so:
Code: |
if ((int32)(val*100 +0.49999) == 123)
|
Which will take the float value, multiply it by 100,add 0.49999 (so that 1.236xxx will become 124xxxx), and tun it into an integer for the comparison.
The internal ceil, and floor functions, can also be used on the value*100, but the comparison will be less accurate, and slower.
Best Wishes |
Thanks for your reply.
I must use float variables!
I already used ceil function but it returns me an error:
"a #device required before this line" in CCS compiler open automatically math.h library...don't know why!! |
|
![](templates/subSilver/images/spacer.gif) |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|