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

92
Vistas
Truncate a number
function truncDigits(inputNumber, digits) {
const fact = 10 ** digits;
return Math.trunc(inputNumber * fact) / fact;
}
truncDigits(27624.399999999998,2) //27624.4 but I want 27624.39

I need to truncate a float value but don't wanna round it off. For example 27624.399999999998 // 27624.39 expected result

Also Math.trunc gives the integer part right but when you Math.trunc value 2762439.99 it does not give the integer part but gives the round off value i.e 2762434

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Probably a naive way to do it:

function truncDigits(inputNumber, digits) {
  return +inputNumber.toString().split('.').map((v,i) => i ? v.slice(0, digits) : v).join('.');
}
console.log(truncDigits(27624.399999999998,2))

At least it does what you asked though

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this:

function truncDigits(inputNumber, digits){  
   return parseFloat((inputNumber).toFixed(digits));
}
truncDigits(27624.399999999998,2)

Your inputs are number (if you are using typescript). The method toFixed(n) truncates your number in a maximum of n digits after the decimal point and returns it as a string. Then you convert this with parseFloat and you have your number.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can try to convert to a string and then use a RegExp to extract the required decimals

function truncDigits(inputNumber: number, digits: number) {
 const match = inputNumber.toString().match(new RegExp(`^\\d+\\.[\\d]{0,${digits}}`))

 if (!match) {
   return inputNumber
 }

 return parseFloat(match[0])
}

Note: I'm using the string version of the RegExp ctor as the literal one doesn't allow for dynamic params.

about 4 years ago · Juan Pablo Isaza 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