It seems that there's a sporadic fault in the @Round function in Xpages SSJS.  I have a piece of code that calculates a number and is supposed to display the value, rounded to two decimal places in a tooltip on the page.  We rounded the number with @Round(value,0.01), and it worked just fine in testing - rounded all the values we threw at it as expected.  But our customer reported sporadic incidents where the rounding clearly wasn't working.  So I did some digging - and here's what I found.

The calculated number to be rounded to 2DP was 26.811000000000003  (that's 11 zeros).     That's a value I found generated the issue in testing - there are other values we've seen reported that don't round properly, and all of them have a long string of zeros before a non-zero digit at the right end.

Some quick testing showed me that
  • @Round(value,0.1) gives 26.8. Correct.
  • @Round(value,0.001) gives 26.811. Also correct.
  • @Round(value,0.01) gives 26.810000000000002 (12 zeros).  Not correct - though it has managed to alter the value, and has the first two DPs correct.

Some Googling suggested that @Round has been under suspicion before.     eOffice's blog has a post describing using Math.Round instead of @Round for some other purpose.   But Math.Round rounds at the decimal point only.   Julian Buss though showed how to move the rounding point about - so simple!  And that gave me the idea for the workround I used, which just moves the effective digit that @Round works at to somewhere where it appears to work.  

My workround was this: @Round(value*100,1)/100: which works fine - or at least it does for  26.811000000000003.  But rounding to two decimal places is probably the commonest use of rounding, so the fact that there's an issue here is really is a bit of a worry.


Comments (5)
Mick Moignard November 20th, 2009 04:17:10 AM