1
I’m with a Javascript code from an API where I’m getting a number with enough digits after the point:
39.576911261669586
I wanted to assign this number to a variable showing only 4 digits, this way:
39.57
Thank you for your attention.
1
I’m with a Javascript code from an API where I’m getting a number with enough digits after the point:
39.576911261669586
I wanted to assign this number to a variable showing only 4 digits, this way:
39.57
Thank you for your attention.
2
1
Buddy, use .toFixed()
for that reason:
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 kind comes to information (of the type number or string), will be converted into number to be used in.toFixed()
(.toFixed()
is not string compatible). Instead ofNumber()
, can also be usedparseFloat()
.
Note: .toFixed(2)
will round the second digit to the largest if the subsequent number of the original (in this case the third digit after the point) is greater than or equal to 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 pick up exactly the amount (without rounding up), you can do so:
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
0
Voce can do so:
parseFloat('39.576911261669586').toFixed(2)
Browser other questions tagged javascript api
You are not signed in. Login or sign up in order to post.
Math.floor
it wasn’t easier to just pick up the whole part ?– Isac
@Isac Truth. I already changed the answer. Obg!
– Sam