How do I get a number with 1 decimal without rounding in javascript?

2

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 !!

    
asked by Santiago Roldan 08.09.2017 в 15:23
source

3 answers

1

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];
    
answered by 08.09.2017 / 15:29
source
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 ) );
    
answered by 08.09.2017 в 16:20
0

To get only 1 unrounded decimal, you can do the following:

  • First we multiply the number by 10 , so we move the decimal point one place to the right
  • Then, we get the whole part of the new number ( eg: parseInt ).
  • Finally we divide it again by 10 , in order to obtain 1 only decimal.

Demo:

var num = 2.7607;
console.log(parseInt(num * 10, 10) / 10);

Optional:

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));
    
answered by 08.09.2017 в 20:29