Thursday, February 16, 2012

sprintf, printf bug in Groovy

Recently I found strange issue when running Grails application on Linux. Sometimes, when formatting decimal number with sprintf it does not work and simply returned original number. After some investigation I found that this is general Groovy behavior and simple script with:

println sprintf('%.2f', 1/609)

returns 0.0016420361 as result, when it suppose to return just 0.00. I was not able to reproduce this bug on Windows or in plain Java, so most probably this is GDK issue, but I didn't investigated it very carefully.
Anyway, this is very easy to fix by casting numbers into decimals explicitly, so this code:

println sprintf('%.2f', 1d/609)

returns nice and correct results.

No comments:

Post a Comment