Chunky Chunk
Chunky Chunk

Reputation: 17217

ActionScript - Formatting Zero With NumberFormatter?

i've assigned properties to a NumberFormatter object so that formatted values contain a leading zero, trailing zeros and a 2 decimal places.

the formatting works unless the number being formatted is 0. how can i format a 0 with the set properties so that 0 becomes 0.00?

var numFormat:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT);
numFormat.leadingZero = true;
numFormat.trailingZeros = true;
numFormat.fractionalDigits = 2;

trace(numFormat.formatNumber(46));      //46.00
trace(numFormat.formatNumber(0.556849));  //0.56
trace(numFormat.formatNumber(0));        //0

[EDIT] i've remedied this problem by manually appending the locale decimal separator with the desired number of fractionalDigits if the formatted number is 0:

if (myFormattedNumber.text == "0" && numFormat.fractionalDigits)
   {
   myFormattedNumber.appendText(numFormat.decimalSeparator);

   for (var i:uint = 0; i < numFormat.fractionalDigits; i++)
       myFormattedNumber.appendText("0");
   }

i'm still very interested in knowing if this is a bug or a feature, but it seems like a oversight to me.

Upvotes: 2

Views: 4138

Answers (2)

Sean Fujiwara
Sean Fujiwara

Reputation: 4546

How about Number(value).toFixed(2) ?

Upvotes: 1

TNC
TNC

Reputation: 5386

It's not sexy, but this was similar to what I used when I ran into a similar issue:

function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String 
{
    var i:int = 0, inc:Number = Math.pow(10, maxDecimals), str:String = String(Math.round(inc * Number(number))/inc);
    var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
    var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
    if (forceDecimals) for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
    while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
    return str.substr(0, sep - i) + ret;
}


trace("zero: " + numberFormat(0, 2, true, false))

Full article here

Upvotes: 1

Related Questions