# Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

### DarkBASIC Discussion / Function for Rounding Floating Point Variables Explained

Message
Posted: 24th Feb 2011 01:23 Edited at: 24th Feb 2011 01:26
I think this was posted a while back (I remember there was a little contest to see who could write the best function ) but I've written it again with comments explaining each step. Sorry for using the same variable names over and over, that was probably confusing but it seemed more efficient to me for some reason well it's sparing a tiny bit of memory I suppose!

Everything worthwhile requires effort.
Posted: 30th Mar 2011 00:05
You dont have an good code to round an float to closest 0.5 ?

i want 1.4 to be rounded to 1.5 and 1.2 rounded to 1.0 if you understand wath iam after
Posted: 30th Mar 2011 01:29
To round to the nearest half takes quite a simple modification of the code

We simply double n# at the start (I stored this in m#) and then divide our answer (c#) by two at the end.
The reason this works is because when we multiply a half by two, it becomes a whole number, using this quality we can treat rounding to the nearest half in the exact same way as rounding to the nearest whole number by tricking the function into treating halves as whole numbers! The result at the end will always end in .0 or .5 because that is what happens to any integer divided by two.

Everything worthwhile requires effort.
Posted: 30th Mar 2011 20:00
Thanks!
Always good to have people that actually can code
Iam only an happy hobby programmer that think its fun