How to indicate a maximum of digits in a var in JavaScript [duplicate]

1

I have a JavaScript code one where I'm getting a number API with enough digits after the point:

39.576911261669586

I wanted to assign that number to a variable showing only 4 digits, like this:

39.57

Thanks for your attention.

    
asked by anonymous 05.10.2017 / 00:42

3 answers

1

Friend, use .toFixed() for this:

numero = 39.576911261669586; // poderia ser também numero = "39.576911261669586";
numero = Number(numero).toFixed(2); // irá retornar 39.58
  

The advantage of using Number() is that, no matter what type   information (of type number or string ), it will be converted into    number to be used in .toFixed() ( .toFixed() is not compatible with strings). Instead of Number() , you can also use parseFloat() .

Note: .toFixed(2) will round the second digit to a larger case if the subsequent number of the original (in this case, the third digit after the dot) is equal to or greater than 5.

numero = 39.576911261669586; // poderia ser também numero = "39.576911261669586";
numero = Number(numero).toFixed(2);
console.log(numero); // irá retornar 39.58

If you want to get exactly the value (without rounding), you can do this:

numero = "39.576911261669586";  // poderia ser também: numero = 39.576911261669586;
numero_decimais = (numero-Math.floor(numero)).toString();
numero_decimais = numero_decimais.substring(1,4);
numero = Math.floor(numero)+numero_decimais;
console.log(numero); // irá retornar 39.57

numero = "39.576911261669586"; // poderia ser também: numero = 39.576911261669586;
numero_decimais = (numero-Math.floor(numero)).toString();
numero_decimais = numero_decimais.substring(1,4);
numero = Math.floor(numero)+numero_decimais;
	console.log(numero); // irá retornar 39.57
    
05.10.2017 / 00:48
2

var num = 39.576911261669586;
console.log (num.toPrecision(4));
  

The toPrecision () method formats a number with a specified length (including the left and right digits of the decimal point) that should be displayed.

    
05.10.2017 / 02:06
0

You can do this:

parseFloat('39.576911261669586').toFixed(2)
    
05.10.2017 / 00:48