JavaScript - SEPARADOR DE MILES

 
Vista:
sin imagen de perfil

SEPARADOR DE MILES

Publicado por martin (14 intervenciones) el 11/01/2021 20:29:51
HOLA AMIGOS DEL FOR TENGO UN INPUT TRADICIONAL EN DONDE VOY INTRODUCIENDO UN NUMERO
Y AMEDIDA QUE VOY TECLEANDO NECESITO DARLE FORMATO CON JAVA SCRIPT DE LA SIGUIENTE MANERA
1
10
100
1,000
10,000
100,100
1,000,000
10,000,000
100,000,000
1000,000,000

TAL VES SE PODRIA UTILIZAR EL EVENTO KEY UP EN UN IMPUT

<INPUT ID="NUMERO" VALUE=''>

PODRIAN AYUDARME POR FAVOR?
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 12/01/2021 00:23:44
Creo que esto resuelve tu problema


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE HTML>
<html>
    <head>
        <title>FORMATEAR UN INPUT NUMERICO SEGUN SE TECLEA UN VALOR</title>
    </head>
    <body>
        <h2>FORMATEAR UN INPUT NUMERICO SEGUN SE TECLEA UN VALOR</h2>
        <table>
            <tr>
                <td>Integer(auto formato con comas para millares)</td>
                <td><input id="inputFormatoNumerico"></td>
            </tr>
        </table>
        <script>
            /**
             * Number.prototype.format(n, x, s, c)
             *
             * @param integer n: length of decimal
             * @param integer x: length of whole part
             * @param mixed   s: sections delimiter
             * @param mixed   c: decimal delimiter
             * sample:
             * let numbers = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345.67, 123456.789];
             * console.log(numbers[6].format(0, 3, ',', '.'); output --> 1,234,567
             * console.log(numbers[8].format(2, 3, ',', '.'); output --> 123,456.78
             */
            Number.prototype.format = function(n, x, s, c) {
                let re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
                    num = this.toFixed(Math.max(0, ~~n));
                return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
            };
            // Restricts input for the given textbox to the given inputFilter.
            function setInputFilter(textbox, inputFilter) {
                ["input"].forEach(function(event) {
                    textbox.addEventListener(event, function() {
                        if (this.id === "inputFormatoNumerico") {
                            if (this.value !== "") {
                                let str = this.value;
                                let oldstr= str.substring(0, str.length - 1);
                                let millares = ",";
                                let decimales = ".";
                                str = str.split(millares).join("");
                                if (isNaN(str)) {
                                    this.value = oldstr;
                                } else {
                                    let numero = parseInt(str);
                                    this.value = numero.format(0, 3, millares, decimales);
                                }
                            }
                        }
                    });
                });
            }
            setInputFilter(document.getElementById("inputFormatoNumerico"), function(value) {
                //declare an object RegExp
                let regex = new RegExp(/^-?\d*$/);
                //test the regexp
                return regex.test(value);
            });
        </script>
    </body>
</html>

Espero que te funcione a la perfección.
Si el input es un campo de un formulario supongo que al hacer el submit tienes que quitar el formato al valor del input y enviarlo sin los separadores de millar.

Se puede probar en JSFiddle.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

SEPARADOR DE MILES

Publicado por martin (14 intervenciones) el 12/01/2021 02:45:08
HOLA AITOR SI FUNCIONA PERFECTAMENTE SOLO LE FALTA UN PEQUEÑO DETALLE, DEBE PERMITIME INTRODUCIR LOS DECIMALES POR EJEMPLO:

100,000.78

FINAL DEBERIA PERMITIRMR INTRODUCIR .78 CENTAVOS DE DOLAR

SI ME PODES DAR UNA MANOS POR FAVOR YA QUE NO TENGO TANTA EXPERIENCIA JAVASCRIPT

DESDE YA MUCHAS GRACIAS
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

SEPARADOR DE MILES

Publicado por martin (14 intervenciones) el 12/01/2021 21:09:48
hola info gracias por la ayuda pero el ejemplo que subiste no funciona tiene errores, acabo de probarlo y no funciona :-(

sera que podes ayudarme por favor? De repente si podes subir una vercion del codigo que funcione bien?

por favor
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de info
Val: 606
Bronce
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por info (45 intervenciones) el 13/01/2021 07:54:58
Hola Martin, a que errores haces referencia? me puedes comentar con mas detalle para poder solucionarlo?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

SEPARADOR DE MILES

Publicado por martin (14 intervenciones) el 13/01/2021 12:40:12
hola info buen dia si te esplico, lo que hice fue tomar el codigo completo y copiarlo a un archivo .php luego al probar introduzco cualquier valor y actua de la siguiente manera

10.00000000000
25.2563256
13.0008965

al introducir un valor siempre coloca el punto en el tercer lugar y ahi se queda lo que necesitaria seria lo siguiente

10,000,000.78
33,256.34
8,000.15

la coma como separador de miles y si fuere necesario deberia permitirme introducir el punto . para los decimales

Si podes ayudarme por favor
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de joel
Val: 3.506
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por joel (895 intervenciones) el 13/01/2021 12:57:09
Ha, si, si, eso es porque coje el locale de tu maquina...
modifica esta linea:
1
contenido[0] = contenido[0].length ? new Intl.NumberFormat().format(parseInt(contenido[0])) : "0";
por esta:
1
contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";

ya nos dirás...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 13/01/2021 13:15:03
Hola Joel.
Que ocurre con los números negativos ya que no acepta el carácter minus "-"?
Supongo que antes de procesar el numero habría que ver si el primer carácter es un carácter "-" y quitarlo, luego procesar el resto y añadirlo al resultado final o hacer una regla diferente (regexp) si se quieren todo tipo de números +/- (positivos o negativos) o solo positivos (+). Tal vez añadiendo otra clase a la clase number o haciendo 2 numberpositivo y numberindistinto.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 13/01/2021 13:40:17
Hola Joel
Como continuación y ya de paso porque no modificar el programa para distinguir entre números enteros y números con decimales permitiendo el uso del signo "." o no., tal vez añadiendo otras 2 clases integerpositivo e integerindistinto.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

SEPARADOR DE MILES

Publicado por martin (14 intervenciones) el 13/01/2021 13:56:34
hola joel ahora si esta funcionando perfecto.
Muchisimas gracias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de info
Val: 606
Bronce
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por info (45 intervenciones) el 13/01/2021 15:41:45
Gracias Joel por comentarlo... ya he modificado el código con esa mejora...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de info
Val: 606
Bronce
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por info (45 intervenciones) el 13/01/2021 15:42:10
Hola Aitor, si, tienes toda la razon, no lo tuve en cuenta... voy a ver como lo soluciono para poner valores negativos...

Sobre lo que comentas del punto separador de decimales, esto ya lo hace... ya funcionan los decimales, no?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 13/01/2021 16:25:19
Hola Joel

Yo añadiría las siguientes funcionalidades para formatear números según se escriben.

(integers) Enteros Indistintos (+/-) (no permite el signo "." de decimales)
(integers) Enteros Positivos (+)>=0 ( no permite el signo "." de decimales, no permite el signo"-" de negativos)

(Float) Números Indistintos (+/-) con 2 decimales fijos (después de introducir el "." solo se pueden introducir 2 cifras)
(Float) Números Positivos (+)>=0 con 2 decimales fijos (no permite el signo"-" de negativos, después de introducir el "." solo se pueden introducir 2 cifras)

Una opción (por ejemplo con una variable global) para distinguir entre sistemas que utilizan el signo "coma" para separar miles y el "punto" para separar decimales de otro sistema que utiliza el "punto" para separar miles y la "coma" para separar decimales.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 13/01/2021 19:25:54
Aquí dejo la rutina que resuelve todo lo comentado anteriormente y se puede probar en :

JSFiddle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <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(+)&gt;= 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(+)&gt;= 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 (+)&gt;= 0</td>
                <td><input class="numberPositivoFixed"></td>
            </tr>
        </table>
        <script>
            // Formatear numeros enteros indistintamente tanto positivos como negativos
            function integerFormatIndistinto(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let caracterInicial = this.value.substring(0, 1);
                let contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\.]/g, "").split(".") : this.value.replace(/[^0-9\.]/g, "").split(".");
                // añadimos los separadores de miles al primer numero del array
                contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
                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 enteros positivos
            function integerFormatPositivo(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let contenido = this.value.replace(/[^0-9\.]/g, "").split(".");
                // añadimos los separadores de miles al primer numero del array
                contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
            }
            // Formatear numeros decimales indistintamente tanto positivos como negativos
            function numberFormatIndistinto(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let caracterInicial = this.value.substring(0, 1);
                let contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\.]/g, "").split(".") : this.value.replace(/[^0-9\.]/g, "").split(".");
                // añadimos los separadores de miles al primer numero del array
                contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
                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 === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let contenido = this.value.replace(/[^0-9\.]/g, "").split(".");
                // añadimos los separadores de miles al primer numero del array
                contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
            }
            // Formatear numeros decimales indistintamente tanto positivos como negativos con solo 2 decimales
            function numberFormatIndistintoFixed(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let caracterInicial = this.value.substring(0, 1);
                let contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\.]/g, "").split(".") : this.value.replace(/[^0-9\.]/g, "").split(".");
                //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 al primer numero del array
                contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
                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 === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let contenido = this.value.replace(/[^0-9\.]/g, "").split(".");
                //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 al primer numero del array
                contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
            }
            window.onload = function() {
                //SE EJECUTA DESPUES CARGAR EL CODIGO CSS y HTML
                // Creamos el evento keyup
                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>

Cualquier comentario para mejorar la rutina es bienvenido.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 13/01/2021 20:37:19
Solución a algún error no considerado y mejoras para probar en:

JSFiddle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <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(+)&gt;= 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(+)&gt;= 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 (+)&gt;= 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 MILLARES=",";
            const DECIMALES=".";
            const DTFLOCAL = new Intl.NumberFormat('en-US');
            //Para coma decimal y punto en millares (ESPAÑA)
            //const MILLARES=".";
            //const DECIMALES=",";
            //const DTFLOCAL = new Intl.NumberFormat('es-ES');
            // Formatear numeros enteros indistintamente tanto positivos como negativos
            function integerFormatIndistinto(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let caracterInicial = this.value.substring(0, 1);
                let contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9]/g, "") : this.value.replace(/[^0-9]/g, "");
                // añadimos los separadores de miles al primer numero del array
                contenido = contenido.length ? DTFLOCAL.format(parseInt(contenido)) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length ? contenido : "0";
                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 enteros positivos
            function integerFormatPositivo(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let contenido = this.value.replace(/[^0-9]/g, "");
                // añadimos los separadores de miles al primer numero del array
                contenido = contenido.length ? DTFLOCAL.format(parseInt(contenido)) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length ? contenido : "0";
            }
            // Formatear numeros decimales indistintamente tanto positivos como negativos
            function numberFormatIndistinto(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let caracterInicial = this.value.substring(0, 1);
                let contenido="";
                if (MILLARES===","){
                    contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\.]/g, "").split(".") : this.value.replace(/[^0-9\.]/g, "").split(".");
                }else{
                    contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\,]/g, "").split(",") : this.value.replace(/[^0-9\,]/g, "").split(",");
                }
                // añadimos los separadores de miles al primer numero del array
                contenido[0] = contenido[0].length ? DTFLOCAL.format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
                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 === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let contenido="";
                if (MILLARES===","){
                    contenido =  this.value.replace(/[^0-9\.]/g, "").split(".");
                }else{
                    contenido =  this.value.replace(/[^0-9\,]/g, "").split(",");
                }
                // añadimos los separadores de miles al primer numero del array
                contenido[0] = contenido[0].length ? DTFLOCAL.format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
            }
            // Formatear numeros decimales indistintamente tanto positivos como negativos con solo 2 decimales
            function numberFormatIndistintoFixed(e) {
                if (this.value === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let caracterInicial = this.value.substring(0, 1);
                let contenido="";
                if (MILLARES===","){
                    contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\.]/g, "").split(".") : this.value.replace(/[^0-9\.]/g, "").split(".");
                }else{
                    contenido = (caracterInicial === "-") ? this.value.substring(1, this.value.length).replace(/[^0-9\,]/g, "").split(",") : this.value.replace(/[^0-9\,]/g, "").split(",");
                }
               //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 al primer numero del array
                contenido[0] = contenido[0].length ? DTFLOCAL.format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
                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 === "") {
                    return;
                }
                // Obtenemos un array con el numero y los decimales si hay
                let contenido="";
                if (MILLARES===","){
                    contenido = this.value.replace(/[^0-9\.]/g, "").split(".");
                }else{
                    contenido = this.value.replace(/[^0-9\,]/g, "").split(",");
                }
                //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 al primer numero del array
                contenido[0] = contenido[0].length ? DTFLOCAL.format(parseInt(contenido[0])) : "0";
                // Juntamos el numero con los decimales si hay decimales
                this.value = contenido.length > 1 ? contenido.slice(0, 2).join(".") : contenido[0];
            }
            window.onload = function() {
                //SE EJECUTA DESPUES CARGAR EL CODIGO CSS y HTML
                // Creamos el evento keyup
                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>

6NBQ1Bo

Espero que sea de utilidad.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de Aitor
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

SEPARADOR DE MILES

Publicado por Aitor (8 intervenciones) el 14/01/2021 01:11:40
Ultima versión con las mejoras de definición de formato en ESPAÑA y USA y corrección de errores con depuración del código.

Se puede probar en : JSFiddle


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<!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(+)&gt;= 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(+)&gt;= 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 (+)&gt;= 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>

Cualquier error comentar.

espero se a de utilidad.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

SEPARADOR DE MILES

Publicado por martin (14 intervenciones) el 14/01/2021 01:29:01
hola aitor exelente aporte probe el codigo en la nuve y de manera local y funciona perfectamente sin errores
gracias
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar