I have a problem with decimals, since I'm getting a number for example 2.7607 and I'm taking out 1 decimal with the function toFixed (1) but it returns 2.8 since it rounds it but I need 2.7 only.
Someone who can help me please.
Thanks !!
I have a problem with decimals, since I'm getting a number for example 2.7607 and I'm taking out 1 decimal with the function toFixed (1) but it returns 2.8 since it rounds it but I need 2.7 only.
Someone who can help me please.
Thanks !!
You can convert the number to a string and then get the number only to the first decimal place:
num.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0];
I have created a function to trim n
decimal without rounding and without regex
function cortar_decimales_sin_redondear(numFloat, toFixed) {
let isNegative = false;
// Comprobamos si el valor es negativo
if ( numFloat < 0 ) {
numFloat *= -1; // Equivale a Math.abs();
isNegative = true;
}
// Cogemos los valores ANTES del separador y lo convertimos a string
let numFloat_bf = numFloat.toString().split('.')[0];
// Cogemos los valores DESPUÉS del separador y lo convertimos a string
let numFloat_af = numFloat.toString().split('.')[1];
// Retornamos el valor en float
// y añadimos el signo '-' si es negativo
return parseFloat( ( isNegative ? '-': '' ) +
numFloat_bf +
'.' +
// Aquí recortamos los decimales según el valor de 'toFixed'
numFloat_af.slice(0, -numFloat_af.length + toFixed )
);
}
let num1 = '-122.7602347';
let num2 = '122.7602347';
let num3 = 2.2344245245;
let num4 = -2.2344245245;
console.log( cortar_decimales_sin_redondear( num1, 1 ) );
console.log( cortar_decimales_sin_redondear( num2, 1 ) );
console.log( cortar_decimales_sin_redondear( num3, 1 ) );
console.log( cortar_decimales_sin_redondear( num4, 1 ) );
To get only 1 unrounded decimal, you can do the following:
10
, so we move the decimal point one place to the right eg: parseInt
). 10
, in order to obtain 1
only decimal.
var num = 2.7607;
console.log(parseInt(num * 10, 10) / 10);
If you would like n
decimals without rounding, then you could do it like this:
function myRound(num, dec) {
var exp = Math.pow(10, dec || 2); // 2 decimales por defecto
return parseInt(num * exp, 10) / exp;
}
var num = 2.7617;
console.log('Con 1 decimales:', myRound(num, 1));
console.log('Con 2 decimales:', myRound(num));
console.log('Con 3 decimales:', myRound(num, 3));