I found this post on rounding via my RSS reader and started giggling since I myself wrestled with this problem a while back. I too started out with string operations etc. but ended up (after some discussion at the office) with a very easy solution.
The below code is in Java but should be easily convertable to JavaScript or any other language that allows you to round a number… The v-variable is a float holding the value we would like to round to .0 or .5:
int value = Math.round(v * 2); float result = (float)value / 2;
It’s so simple it’s scary…
Update 3 May 2006: Updated the code based on feedback in comment.
How can an integer return a .5 value??
Also, when using LotusScript’s round function, pay close attention to its very … err … special approach:
“If the first non-significant digit is 5, and all subsequent digits are 0, the last significant digit is rounded to the nearest even digit.”
That means, that Round(2.4500, 1) will actually return 2.4, while Round(2.5500, 1) will return 2.6!! Since it’s well documentet, we can’t call it a bug, though …
Well you’re right it can’t! It is because I combined two lines of code without thinking… I’ll correct the code. Thanks.
Julian has written a very interesting article on rounding numbers a while back. Go check it out if your’e really into rounding!
Julian is my hero, but in this case I tend to disagree. There is no such thing as “right” or “wrong” rounding. It’s purely a matter of convention. And most definitely, the common understanding of business users is, that .5 is always rounded up, but never down. At least in Europe …
You truely are awesome for putting that on this website, the simple things matter dude, I was having a hell of a time figuring out that rounding issue, and its sooo simple… hahaha…
Thanks man…