Obtener la porción decimal de un número con JavaScript
Tengo números flotantes como 3.2
y 1.6
.
Necesito separar el número en la parte entera y decimal. Por ejemplo, un valor de 3.2
se dividiría en dos números, es decir, 3
y 0.2
Obtener la porción entera es fácil:
n = Math.floor(n);
Pero estoy teniendo problemas para obtener la porción decimal. He intentado esto:
remainer = n % 2; //obtem a parte decimal do rating
Pero no siempre funciona correctamente.
El código anterior tiene la siguiente salida:
n = 3.1 => remainer = 1.1
Lo que me falta aquí?
16 answers
Use 1
, no 2
.
js> 2.3 % 1
0.2999999999999998
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 18:21:54
var decimal = n - Math.floor(n)
Aunque esto no funcionará para menos números, por lo que podríamos tener que hacer
n = Math.abs(n); // Change to positive
var decimal = n - Math.floor(n)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 18:22:54
Usted podría convertir a cadena, ¿verdad?
n = (n + "").split(".");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-22 20:01:49
¿Cómo es 0.2999999999999998 una respuesta aceptable? Si yo fuera el que pregunta, querría una respuesta .3. Lo que tenemos aquí es precisión falsa, y mis experimentos con piso, %, etc indican que Javascript es aficionado a la precisión falsa para estas operaciones. Así que creo que las respuestas que están utilizando la conversión a cadena están en el camino correcto.
Yo haría esto:
var decPart = (n+"").split(".")[1];
Específicamente, estaba usando 100233.1 y quería la respuesta ".1".
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-02 14:04:56
Una forma sencilla de hacerlo es:
var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals); //Returns 0.20000000000000018
Desafortunadamente, eso no devuelve el valor exacto. Sin embargo, eso se arregla fácilmente:
var x = 3.2;
var decimals = x - Math.floor(x);
console.log(decimals.toFixed(1)); //Returns 0.2
Puede usar esto si no conoce el número de decimales:
var x = 3.2;
var decimals = x - Math.floor(x);
var decimalPlaces = x.toString().split('.')[1].length;
decimals = decimals.toFixed(decimalPlaces);
console.log(decimals); //Returns 0.2
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-02 03:52:14
Así es como lo hago, que creo que es la forma más directa de hacerlo:
var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-04 12:11:21
Lo siguiente funciona independientemente de la configuración regional del separador decimal... en la condición solo se usa un carácter para un separador.
var n = 2015.15;
var integer = Math.floor(n).toString();
var strungNumber = n.toString();
if (integer.length === strungNumber.length)
return "0";
return strungNumber.substring(integer.length + 1);
No es bonito, pero es preciso.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-17 23:17:51
Puede convertirlo en una cadena y usar el método replace
para reemplazar la parte entera con cero, luego convertir el resultado en un número:
var number = 123.123812,
decimals = +number.toString().replace(/^[^\.]+/,'0');
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-27 20:57:56
Dependiendo del uso que le dará después, pero esta solución simple también podría ayudarlo.
No estoy diciendo que sea una buena solución, pero para algunos casos concretos funciona
var a = 10.2
var c = a.toString().split(".")
console.log(c[1] == 2) //True
console.log(c[1] === 2) //False
Pero tomará más tiempo que la solución propuesta por @ Brian M. Hunt
(2.3 % 1).toFixed(4)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-24 08:19:45
Forma independiente del lenguaje:
var a = 3.2;
var fract = a * 10 % 10 /10; //0.2
var integr = a - fract; //3
Tenga en cuenta que solo corrige para números con una longitud fractioanal)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-22 10:35:21
Si la precisión importa y requiere resultados consistentes, aquí hay algunas proposiciones que devolverán la parte decimal de cualquier número como una cadena, incluyendo el "0 inicial.". Si lo necesita como un flotador, simplemente agregue var f = parseFloat( result )
al final.
Si la parte decimal es igual a cero, se devolverá "0.0". Los números Null, Nan y undefined no se prueban.
1. Matriz.split
var nstring = (n + ""),
narray = nstring.split("."),
result = "0." + ( narray.length > 1 ? narray[1] : "0" );
2. Cadena.subcadena, Cuerda.indexOf
var nstring = (n + ""),
nindex = nstring.indexOf("."),
result = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");
3. Matemáticas.piso, Número.toFixed, Cadena.indexOf
var nstring = (n + ""),
nindex = nstring.indexOf("."),
result = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");
4. Matemáticas.piso, Número.toFixed, String.split
var nstring = (n + ""),
narray = nstring.split("."),
result = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");
Aquí hay un enlace de jsPerf: https://jsperf.com/decpart-of-number /
Podemos ver que la proposición #2 es la más rápida.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-17 14:52:14
Puede usar la función parseInt()
para obtener la parte entera que usar eso para extraer la parte decimal
var myNumber = 3.2;
var integerPart = parseInt(myNumber);
var decimalPart = myNumber - integerPart;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-18 07:41:45
Tuve un caso en el que sabía que todos los números en cuestión tendrían solo un decimal y quería obtener la porción decimal como un entero, así que terminé usando este tipo de enfoque:
var number = 3.1,
decimalAsInt = Math.round((number - parseInt(number)) * 10); // returns 1
Esto funciona muy bien también con enteros, devolviendo 0 en esos casos.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-22 12:33:35
Estoy usando:
var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;
if( str.indexOf('.') != -1 ){ //check if has decimal
var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}
Entrada: -556.123444444
Resultado: 123444444
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-16 10:48:17
Después de mirar varios de estos, ahora estoy usando...
var rtnValue = Number(7.23);
var tempDec = ((rtnValue / 1) - Math.floor(rtnValue)).toFixed(2);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-17 17:45:58
float a=3.2;
int b=(int)a; // you'll get output b=3 here;
int c=(int)a-b; // you'll get c=.2 value here
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-14 10:32:33