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

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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