PDA

View Full Version : Problem with if then else


easleyt
03-18-2011, 07:12 PM
Sorry but this is my 1st attempt @ actionscript and I've yet to find a really good reference and training is weeks away. I'm using Flex Builder 3 and trying to create a percentage based on current month sales vs prior month sales and avoiding zero divide for entities with no prior month sales but it isn't compiling, the relevant code is:

private function formatCMCPct(item:Object, column:DataGridColumn) :String {return fmtCMCPct.format(if(item.PMC == 0) {0;}
else {(item.CMC/item.PMC)*100;}) + "%"; }

<mx:NumberFormatter id="fmtCMCPct" precision="0" useThousandsSeparator="true" useNegativeSign="true"/>


When I first tried simply (item.CMC/item.PMC)*100 it worked except for the zero divide rows. The error is as follows:

1083: Syntax error: else is expected
1084: Syntax error: expecting identifier before if
1084: Syntax error: expecting identifier before rightparen
1084: Syntax error: expecting rightparen before leftbrace
1086: Syntax error: expecting semicolon before leftbrace

Thanks!

xxneon
03-18-2011, 07:26 PM
I think you need to break this up a bit.. I don't think you can nest an if statement inside the format() function call like that ..
try it like this.
private function formatCMCPct(item:Object, column:DataGridColumn) :String {
var perc;
if(item.PMC == 0) {
perc = 0;
} else {
perc = (item.CMC/item.PMC)*100;
}
return fmtCMCPct.format(perc) + "%";
}

easleyt
03-18-2011, 08:09 PM
Perfect, thank you

audiopro
03-18-2011, 09:51 PM
Why does an 'if' statement not work inside a function?
First language I have heard if where this happens.

xxneon
03-19-2011, 03:59 AM
i didn't try it but maybe a nested if would work if you strip the ; from the lines inside the if else so that your not confusing the compiler .. normally you don't see a ; inside parens I think it can possibly cause compile errors..

audiopro
03-19-2011, 09:00 AM
Sorry, I hadn't noticed the if statement was inside the parens.