Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
How to retain the first 2 numbers as is after the decimal point. Javascript

I would like to format my numbers to always display 2 decimal places. lets say: I have a number => 21.268998 , the o/p I'm looking is to chop the rest of the decimal point and keep only the first 2 i.e:

21.26

however with the tofixed or toPrecision approach to always rounds to a certain decimal which is causing issues when a number is 99.999999, it rounds to 100.000 which is not right.

var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2); // this is showing correctly

var num2 = "99.99999";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);// this is incorrect=> I want to show 99.99

any idea how to get the first numbers to show always without rounding them off to the next number.

Jsfiidle:

https://jsfiddle.net/8ohvyczg/1/

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

You can use slice method in javascript:

var num2 = 99.99999;
num2 = num2.slice(0, (num2.indexOf("."))+3); 
document.getElementById('num2').innerHTML = num2;
about 4 years ago · Santiago Gelvez Relatório

0

Here's an approach of a simple truncate, and not round off:

var number = 26.4363
var str = number.toString();
console.log(str.substring(0, str.indexOf(".")+3));

about 4 years ago · Santiago Gelvez Relatório

0

Did u tried Math.trunc()?

var num = "99.99999";

var round=(Math.round(num * 100) / 100).toFixed(2)
var trunc=(Math.trunc(num * 100) / 100)
console.log(round);
console.log(trunc);

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda