February 20, 2006

BIG numbers in coldfusion

mark kruger has an interesting post on his blog concerning formatting big numbers in coldfusion. in that post's comments sean corfield points out that the real issue is the precision of the float datatype that coldfusion uses under the covers. this issue has also come up a few times on the support forums and probably the best answer is (as usual) to dip down into the java underlying coldfusion to use one of the Big math classes (java.math.BigInteger, java.math.BigDecimal) to handle the math on the special occasions that you really need that kind of precision. as sean pointed out, float is faster than BigDecimal for calculations so you should use those classes only when they are really needed.

what has this got to do with g11n? well even if you do use those Big math classes, core java's NumberFormat class doesn't understand it's own BigDecimal/BigInteger classes (ie it casts everything back to double/long). so when you come to display these values you're back in the same situation that mark's post describes. what to do? use icu4j of course (everybody knew that was coming). it's NumberFormat class understands BigDecimal/BigInteger plenty fine. for example:

<cfscript>
theNumber="9123456789123456789.123";
//use server default locale nF=createObject("java","com.ibm.icu.text.NumberFormat").getInstance();
cNF=createObject("java","java.text.NumberFormat").getInstance();
bigDecimal=createObject("java","java.math.BigDecimal").init(theNumber);
formattedNumber=nf.format(bigDecimal);
coreJavaFormattedNumber=cNF.format(bigDecimal);
writeoutput("original number:=#theNumber#<br>
   big decimal representation:=#bigDecimal#<br>
   icu4j number Formatted:=#formattedNumber#<br>
   core java number Formatted:=#coreJavaFormattedNumber#"
);
</cfscript>


which outputs:

original number:=9123456789123456789.123
big decimal representation:=9123456789123456789.123
icu4j number Formatted:=9,123,456,789,123,456,789.123
core java number Formatted:=9,123,456,789,123,457,000


i really wish coldfusion would use icu4j. it would make i18n work much easier and as a side effect help w/problems like this.

0 Comments:

Post a Comment

<< Home