Sign in to follow this  
Followers 0
Riggs

Rounding floating point numbers to nearest integer

6 posts in this topic

Omron CJ1 Is there an easy way to do this? I've been through the instructions with a fine toothed comb and I've not come up with a simple solution... James.

Share this post


Link to post
Share on other sites
Have you tried the FIX instruction, this converts the 32-bit Floating Point value to a 16-bit Integer, without the decimal place of course. Bear in mind, that this always rounds down, if you want it to round up also, you may have to do the old 'add 0.5' trick...

Share this post


Link to post
Share on other sites
Cheers Lostcontrol, I'm using the FIX instruction elsewhere in the program. Trouble is, it only returns the integer part and throws the rest away, as you say. So I need a way of finding out if the bit beyond the decimal point is greater or less than 0.5, in order to decide whether to round up or down. The only way I've come up with so far is to FIX the real number into an int, then FLT it back into a real and subtract this from the original number, then use a comparison instruction to see if what is left is bigger than 0.5 or not. If so then add 1. All seems a bit long winded, but maybe there isn't a better way? James.

Share this post


Link to post
Share on other sites
Depending on what you do with this number, maybe you could multiply by 10 before convert it to integer and work with this....

Share this post


Link to post
Share on other sites
Definitely seems long winded, what are you trying to achieve? 1. If the Real value is 231.45, then FIX'ed, this will be 231, 2. If the Real value is 231.55, then FIX'ed, this will be 231. If you add 0.5 before the FIX, the Real will become 232.15, which when FIX'ed, = 232.

Share this post


Link to post
Share on other sites
Cheers Lostcontrol, Your 'Add 0.5 then FIX' hadn't clicked...brilliant, I'll do that. Thanks! James.

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  
Followers 0