SVicente's Blog

Follow me and you'll know what I like to do

Javascript – formatar números (Brasil, pt-BR)

Criei o seguinte código:

var _DECIMAL_POINT=','; // modify according to regional settings: . or ,

// this function was created by myself (svicente99@yahoo.com)
// date: 2011, Apr.15th
// ----------------------------------------------------------
function fmt_number_BR(v) {

// primeiro retira caracteres invalidos da string "v"
var VALIDOS="0123456789.";
var vl = "", posDec, aux;
var vInt, vDec;

for (var i=0; i =0)
vl += v.substring(i,i+1);
}
posDec = vl.indexOf('.');
if( posDec >= 0 )
{
vInt = vl.substring(0, posDec);
vDec = _DECIMAL_POINT + vl.substring(posDec+1, vl.length);
}
else{
vInt = vl;
vDec = "";
}
v = "";
n = vInt.length;
if( posDec==0 ) vInt = "0";
j = 1;
do{
v = vInt.substr(n-1,1) + v;
if (j%3==0 && n>1) {
v='.'+v; j = 0;
}
n--; j++;
} while(n>0);
return( v + vDec );
}

function show_format(vl) {
document.write("" + vl + " ==> " + fmt_number_BR(vl) + "
");
}

show_format('24998930114.02323333');
show_format('2499832343120');
show_format('2.023333');
show_format('999');
show_format('0.15');
show_format('1000');
show_format('10');
show_format('0');
show_format('200,001');
show_format('2390435091.000');
show_format('390435091.000');
show_format('12,345.67');
show_format('.1');
show_format('.1349830');
show_format('234.1349830');

Para testar um nº próprio, digite e tecle [TAB]: 

 


Se quiser, teste online.

Deixe seus comentários. Use à vontade; agradeço por citar meus créditos.

April 16, 2011 - Posted by | Web Development | , , , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: