Segue uma função JavaScript para formatação de dados numéricos para controles Input (TextBox).
A chamada à função deve ser feita no evento onKeyPress.
Para conseguir este formato: 1.234.567,89
this.TextBox1.Attributes.Add("onKeyPress", "return(medidaFormat(this,'.',2,event))");
// Formata texto tipo medida
// Parâmetros:
// fld = Componente a ser varrido
// milSep = Separador de milhar, caso não haja passar branco ('')
// maxDecimais = número máximo de casas decimais
// e = Argumentos do Evento
function medidaFormat(fld, milSep, maxDecimais, e)
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var decimais = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Delete
if (whichCode == 0) return true;
key = String.fromCharCode(whichCode); // Pega o valor da tecla digitada
if (strCheck.indexOf(key) == -1) return false; // Não é uma chave válida
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != ',')) break; // Verifica se o valor é 0 ou ,
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if(len == maxDecimais) // Se tamanho for igual não precisa preencher com zeros
{
fld.value = '0,' + aux;
}
else if(len <= maxDecimais) //Se for menor preencher decimais com zeros a esquerda
{
for(i=len; i <= maxDecimais-1; i++) //Preenche os decimais de acordo com o número de casas
{
decimais += '0';
}
fld.value = '0,' + decimais + aux;
}
if (len > maxDecimais)// Se for maior, percorrer nros não decimais para formatação de ordem de números e milhar
{
aux2 = '';
for (z = len - maxDecimais, j = 0, i = len - maxDecimais; i > 0; i--)
{
if (j == 3)
{
aux2 = milSep + aux2;
j = 0;
}
z--;
aux2 = aux.charAt(z) + aux2;
j++;
}
if( (aux2.length + (maxDecimais + 1)) <= fld.maxLength )
{
fld.value = '';
len2 = aux2.length;
for (i = 0 ; i <= len2 - 1; i++)
fld.value += aux2.charAt(i);
fld.value += ',' + aux.substr(len - maxDecimais, len);
}
}
return false;
}