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

382
Visualizações
Is it a bad practice to use methods like Number() String() in javascript or we shall use other ways as shown below and try to minimize their use?

  let num = 231.32;
  console.log( num.toPrecision() );
  console.log( String(num) );
  
  {

  let numStr = "250";
  console.log(Number(numStr)); console.log(Number.parseFloat(numStr));

}

  
Here we can achieve same things that String() and Number() can do by other ways. The above code gives same output. So shall we try to minimize the use case of String() and Number(). Which one would be nice ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is never really a real bad method just depends on the situation you are working on.

ToPrecision() will change the original number and round to specific decimal: Note that ToPrecision() could only deal with number and will produce error with deal with string.

The toPrecision() method returns a string representing the Number object to the specified precision

Number v.s ParseFloat is almost the same in most of the situation, but Number will return NaN and parseFloat will return the number part when deal with a string that contain some characters and number. (e.g 123ABC)

Example:

let num = '123ABC'
//return 123
console.log(parseFloat(num))
//return NaN
console.log(Number(num))

let num1='123'
 //Produce error
console.log(num1.toPrecision(2))

I think the main difference between String and use " " is that you can't always and it is very annoying to redeclare the things you want (e.g. redeclare ABC to "ABC"). (I think your numStr is to show use " " change string.

Another built-in function to use is toString() to convert to string, but toString will produce error when you use want to convert null and undefined.

Example:

let test = undefined;
//produce 'undefined'
console.log(String(test))
//produce error
console.log(test.toString())

I think it is OK to use any of them in the most situation, but you have to notice the small difference. They are not totally same.

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