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.
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.
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 ofNumber()
, you can also useparseFloat()
.
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
You can do this:
parseFloat('39.576911261669586').toFixed(2)