thecfguy

A Unique Developer

Problem with Real Number operation and dollarFormat function

Today I come across really strange problem. I am just trying to execute following code.

<cfset invoiceAmount=75.00><cfset paidAmount=73.12><cfset discount=1.88><cfset dueBalance = invoiceAmount - paidAmount - discount><cfoutput>Balance Due: #dollarFormat(dueBalance)#</cfoutput>

What should be result? Ofcourse Balance Due: $0.00 (what a stupid question?). Even I have thought same but result is really surprising and its Negative Zero
Output:
Balance Due: ($0.00)

This is because of rounding problem of mathematical operation on Real number. Subtract operation on above numbers (invoiceAmount - paidAmount - discount) produce -4.4408920985E-015 as result which is almost zero (but not zero). Now I was applying dollarFormat function which display number to upto two decimal point (not rounding to two decimal point) so result is -0.00 and will display as ($0.00).

Best solution I found is to apply Round function on number prior to apply dollarFormat function. I have just tried below one and it work for me.

<cfset invoiceAmount=75.00><cfset paidAmount=73.12><cfset discount=1.88><cfset dueBalance = invoiceAmount - paidAmount - discount><cfoutput>    Balance Due: #dollarFormat(Round(dueBalance*1000)/1000)#</cfoutput>

Round(dueBalance*1000)/1000.00 is work fine for me to display what exactly I want (instead of NEGATIVE ZERO). My intension was excluding numbers on 3rd or greater position after decimal point as it was creating problem for me.