Rui Casaca
Rui Casaca

Reputation: 11

Insert commas into string number

I have this code, and I want to put commas.

I've seen many examples, but I dont now were put the code.

This is my AS3 code:

calccn.addEventListener(MouseEvent.CLICK,result1);

function result1(e:MouseEvent)
{

var vev: Number = (Number(vev.text));
var cn1: Number = (Number(3/100));

var result1f: Number = (Number(vev*cn1));
var round;
round=result1f.toFixed(0);
v3.text = String(round);
}

Example If the result give me 1528000,32 I want that the result is 1.528.000 or 1 528 000

Upvotes: 1

Views: 147

Answers (1)

Organis
Organis

Reputation: 7316

I didn't know (live and learn, eh), but there's actually a dedicated class: NumberFormatter.

If you want to do the thing on a regular basis, you might want a method to call:

// Implementation.
import flash.globalization.NumberFormatter;

// The default separator is comma.
function formattedNumber(value:Number, separator:String = ","):String
{
    var NF:NumberFormatter;
    
    NF = new NumberFormatter("en_US");
    
    // Enforce the use of the given separator.
    NF.groupingSeparator = separator;
    
    // Ignore the fraction part.
    NF.fractionalDigits = 0;
    
    return NF.formatNumber(value);
}

// Usage.

//Format the given number with spaces for separator.
trace(formattedNumber(1528000.32, " ")); // 1 528 000

//Format the given number with the default separator.
trace(formattedNumber(1528000.32)); // 1,528,000

But if you want just a simple one-timer, and don't really care if it is commas or spaces as long as they present you may just condense in into a single expression:

calccn.addEventListener(MouseEvent.CLICK, result1);

function result1(e:MouseEvent):void
{
    // Declaring variables with the same names as
    // other entities is a generally bad idea.
    var input:Number = Number(vev.text);
    var cn1:Number = 3.0 / 100.0;
    
    // Keep in mind that I used int() here as
    // a simple tool to remove the fraction part. 
    v3.text = (new NumberFormatter("en_US")).formatNumber(int(input * cn1));
}

Upvotes: 2

Related Questions