How to specify a maximum of digits in a var in Javascript

Asked

Viewed 63 times

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.

3 answers

2

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

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

suporte navegador

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 of Number(), can also be used parseFloat().

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

  • 1

    Math.floor it wasn’t easier to just pick up the whole part ?

  • @Isac Truth. I already changed the answer. Obg!

0

Voce can do so:

parseFloat('39.576911261669586').toFixed(2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.