Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda