Search code examples
coldfusionnumber-formatting

DollarFormat with minus sign in ColdFusion


I'm trying to get a value of -1000 to be formatted at -$1,000.00 in ColdFusion. When using dollarFormat it displays negative numbers in parenthesis like ($1,000.00). when I use numberFormat like so:

numberFormat(-1000,'$');

It displays as -$1000 without the 2 decimal places and comma but displays the minus sign in the correct position. If I try:

numberFormat(-1000,'$_,___.__');

It displays as $-1,000.00 where the minus sign is after the $ sign. If I try:

numberFormat(-1000,'-$_,___.__');

It still displays as $-1,000.00 where the minus sign is after the $ sign.

Seems like if there is no decimal then the minus sign is in the correct position but as soon as you add a decimal then the minus sign comes after the dollar sign. Does anyone know how to get it for format correctly like -$1,000.00?


Solution

  • Use Java's DecimalFormat, which allows one to provide a formatting mask for both positive and negative numbers:

    for (v in [1234,-5678]){
        result = createObject("java", "java.text.DecimalFormat").init("$##,####0.00;-$##,####0.00").format(javacast("double",v));
        writeDump(var=[v, result]);
        writeOutput("<hr>");
    }
    

    Obviously wrap that in a UDF.