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

181
Visualizações
Return decimal number as a Number type javascript

I have a function which adds zeros to a number: for example, we input 10, the output would be 10.00.

The issue is that the result of the function is a string rather than a number type, is there a way to return 10.00 as a number in javascript?

const formatNumber = number => 
  number.toFixed(Math.max(((`${number}`).split('.')[1] || '').length, 2));
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Number.prototype.toFixed() takes only either zero or one arguments. It should return a number after you use it. If it doesn't, for whatever reason, you can use String.prototype.toNumber() to turn it into a Number type.

I can't write comments due to lack of reputation, but I am trying to make my answer as detailed as possible so i can keep this answer.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use toFixed() function here instead of using split() and valueOf() to return a string as a number

<!DOCTYPE html>
<html>
<body>

<p>The toFixed() method returns a string with decimals:</p>

<p id="demo1"></p>

<p>The valueOf() method returns a number as a number:</p>

<p id="demo2"></p>

<script>
let x = 10;

x=x.toFixed(2); //toFixed(2) will return 10 with 2 decimal i.e. 10.00 as a string

document.getElementById("demo1").innerHTML = x;

document.getElementById("demo2").innerHTML = x.valueOf(); // valueOf() will return number here instead of string
</script>

</body>
</html>

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