Thursday, 15 December 2011

One decimal place

This is a small function I wrote to print Numbers to one decimal place. Most user-visible values used in Bug Tunnel Defense were whole numbers and so were stored as int. But a few needed more precision and so were stored as Number. So they did not overflow their TextField they were displayed to one decimal place, using this function.

static function OneDP(fVal:Number):String {
 var iVal1:int, iVal2:int;

 iVal2 = fVal * 10;
 if (iVal2 == 0) {return "0"};
 iVal1 = iVal2 / 10;
 iVal2 = iVal2 - iVal1 * 10;
 if (iVal2 == 0) {return String(iVal1);}
 return String(iVal1) + "." + String(iVal2);

No comments:

Post a Comment