<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FORMATEAR UN INPUT NUMERICO SEGUN SE TECLEA UN VALOR</title>
<style>
input {
padding: 20px;
margin: 10px;
font-size: 18px;
}
.label,
.integerPositivo,
.integerIndistinto,
.numberPositivo,
.numberIndistinto,
.numberPositivoFixed,
.numberIndistintoFixed {
text-align: right;
}
.positivos {
color: black;
}
.negativos {
color: red;
}
</style>
</head>
<body>
<h2>FORMATEAR UN INPUT NUMERICO SEGUN SE TECLEA UN VALOR</h2>
<table>
<tr>
<td class="label">Integer(+/-)</td>
<td><input class="integerIndistinto"></td>
</tr>
<tr>
<td class="label">Integer(+)>= 0</td>
<td><input class="integerPositivo"></td>
</tr>
<tr>
<td class="label">Float(+/-)</td>
<td><input class="numberIndistinto"></td>
</tr>
<tr>
<td class="label">Float(+)>= 0</td>
<td><input class="numberPositivo"></td>
</tr>
<tr>
<td class="label">Float Fixed 2 (+/-)</td>
<td><input class="numberIndistintoFixed"></td>
</tr>
<tr>
<td class="label">Float Fixed 2 (+)>= 0</td>
<td><input class="numberPositivoFixed"></td>
</tr>
</table>
<script>
//variables globales para definir el separador de millares y decimales
//Para coma millares y punto en decimales (USA)
const DECIMALES=".";
// cambiar por "," para coma decimal y punto en millares (ESPAÑA)
const INFLOCAL = DECIMALES==="."?new Intl.NumberFormat('en-US'):new Intl.NumberFormat('es-ES');
//============================================================================
let regexpInteger = new RegExp('[^0-9]', 'g');
let regexpNumber = new RegExp('[^0-9' + '\\' + DECIMALES + ']', 'g');
//============================================================================
// Formatear numeros enteros indistintamente tanto positivos como negativos
function integerFormatIndistinto(e) {
if (this.value !== "") {
//ver si el primer caracter es el simbolo minus "-"
let caracterInicial = this.value.substring(0, 1);
//si hay caracter negativo al inicio se quita del proceso de formateo
//se filtra el contenido de caracteres no admisibles
let contenido = caracterInicial === "-" ? this.value.substring(1, this.value.length).replace(regexpInteger, "") : this.value.replace(regexpInteger, "");
// añadimos los separadores de miles
contenido = contenido.length ? INFLOCAL.format(parseInt(contenido)) : "0";
this.value = contenido.length ? contenido : "0";
// Juntamos el signo "-" minus si existe
if (caracterInicial === "-") {
this.value = caracterInicial + this.value;
}
//damos color rojo si el numero es negativo
this.className = this.value.substring(0, 1) !== "-" ? "numberIndistinto positivos" : "numberIndistinto negativos";
}
}
// Formatear solamente numeros enteros positivos
function integerFormatPositivo(e) {
if (this.value !== "") {
//se filtra el contenido de caracteres no admisibles
let contenido = this.value.replace(regexpInteger, "");
// añadimos los separadores de miles al numero
contenido = contenido.length ? INFLOCAL.format(parseInt(contenido)) : "0";
this.value = contenido.length ? contenido : "0";
}
}
// Formatear numeros decimales indistintamente tanto positivos como negativos
function numberFormatIndistinto(e) {
if (this.value !== "") {
//ver si el primer caracter es el simbolo minus "-"
let caracterInicial = this.value.substring(0, 1);
//si hay caracter negativo al inicio se quita del proceso de formateo
//se filtra el contenido de caracteres no admisibles
//se divide el numero entre la parte entera y la parte decimal
let contenido = caracterInicial === "-" ? this.value.substring(1, this.value.length).replace(regexpNumber, "").split(DECIMALES) : this.value.replace(regexpNumber, "").split(DECIMALES);
// añadimos los separadores de miles a la parte entera del numero
contenido[0] = contenido[0].length ? INFLOCAL.format(parseInt(contenido[0])) : "0";
// Juntamos el numero con los decimales si hay decimales
this.value = contenido.length > 1 ? contenido.slice(0, 2).join(DECIMALES) : contenido[0];
// Juntamos el signo "-" minus si existe
if (caracterInicial === "-") {
this.value = caracterInicial + this.value;
}
//damos color rojo si numero negativo
this.className = this.value.substring(0, 1) !== "-" ? "numberIndistinto positivos" : "numberIndistinto negativos";
}
}
// Formatear solamente numeros decimales positivos
function numberFormatPositivo(e) {
if (this.value !== "") {
//se filtra el contenido de caracteres no admisibles
//se divide el numero entre la parte entera y la parte decimal
let contenido = this.value.replace(regexpNumber, "").split(DECIMALES);
// añadimos los separadores de miles al primer numero del array
contenido[0] = contenido[0].length ? INFLOCAL.format(parseInt(contenido[0])) : "0";
// Juntamos el numero con los decimales si hay decimales
this.value = contenido.length > 1 ? contenido.slice(0, 2).join(DECIMALES) : contenido[0];
}
}
// Formatear numeros decimales indistintamente tanto positivos como negativos con solo 2 decimales
function numberFormatIndistintoFixed(e) {
if (this.value !== "") {
//ver si el primer caracter es el simbolo minus "-"
let caracterInicial = this.value.substring(0, 1);
//si hay caracter negativo al inicio se quita del proceso de formateo
//se filtra el contenido de caracteres no admisibles
//se divide el numero entre la parte entera y la parte decimal
let contenido = caracterInicial === "-" ? this.value.substring(1, this.value.length).replace(regexpNumber, "").split(DECIMALES) : this.value.replace(regexpNumber, "").split(DECIMALES);
//ver si hay ya 2 decimales introducidos
if (contenido.length > 1) {
if (contenido[1].length > 2) {
contenido[1] = contenido[1].substring(0, contenido[1].length - 1);
}
}
// añadimos los separadores de miles a la parte entera del numero
contenido[0] = contenido[0].length ? INFLOCAL.format(parseInt(contenido[0])) : "0";
// Juntamos el numero con los decimales si hay decimales
this.value = contenido.length > 1 ? contenido.slice(0, 2).join(DECIMALES) : contenido[0];
// Juntamos el signo "-" minus si existe
if (caracterInicial === "-") {
this.value = caracterInicial + this.value;
}
//damos color rojo si numero negativo
this.className = this.value.substring(0, 1) !== "-" ? "numberIndistinto positivos" : "numberIndistinto negativos";
}
}
// Formatear solamente numeros decimales positivos con solo 2 decimales
function numberFormatPositivoFixed(e) {
if (this.value !== "") {
//se filtra el contenido de caracteres no admisibles
//se divide el numero entre la parte entera y la parte decimal
let contenido = this.value.replace(regexpNumber, "").split(DECIMALES);
//ver si hay ya 2 decimales introducidos
if (contenido.length > 1) {
if (contenido[1].length > 2) {
contenido[1] = contenido[1].substring(0, contenido[1].length - 1);
}
}
// añadimos los separadores de miles a la parte entera del numero
contenido[0] = contenido[0].length ? INFLOCAL.format(parseInt(contenido[0])) : "0";
// Juntamos el numero con los decimales si hay decimales
this.value = contenido.length > 1 ? contenido.slice(0, 2).join(DECIMALES) : contenido[0];
}
}
window.onload = function() {
//SE EJECUTA DESPUES CARGAR EL CODIGO CSS y HTML
// Creamos el evento keyup para cada clase definida
document.querySelectorAll(".integerIndistinto").forEach(el => el.addEventListener("keyup", integerFormatIndistinto));
document.querySelectorAll(".integerPositivo").forEach(el => el.addEventListener("keyup", integerFormatPositivo));
document.querySelectorAll(".numberIndistinto").forEach(el => el.addEventListener("keyup", numberFormatIndistinto));
document.querySelectorAll(".numberPositivo").forEach(el => el.addEventListener("keyup", numberFormatPositivo));
document.querySelectorAll(".numberIndistintoFixed").forEach(el => el.addEventListener("keyup", numberFormatIndistintoFixed));
document.querySelectorAll(".numberPositivoFixed").forEach(el => el.addEventListener("keyup", numberFormatPositivoFixed));
};
</script>
</body>
</html>