How to format a number using "toFixed" only if it is not integer in Javascript?

Asked

Viewed 40 times

0

I have a function that returns me a number, which can be integer, like: 440; or it can be broken, like 466.1638231521. But I need to have a way to, from the function, find out if the number is broken. If it is whole, I will leave it the way it is, otherwise I will format using toFixed(4).

function geraFrequenciaNota(semitons) {
  let divisor = (semitons / 12)
  let exponenciado = Math.pow(2, divisor)
  let multFreq = 440 * exponenciado
  return multFreq.toFixed(4)
}

That’s my code so far, the problem is that when the number is Integer, for example 440, I want it to return 440, not 440.0000.

  • 1

    The solution is in the questions indicated above in the blue box (although it is not 100% exactly the same, just adapt): for example, multFreq.toLocaleString('en-US', {minimumFractionDigits: 0, maximumFractionDigits: 4}), or the equivalent with Intl.NumberFormat (read the answers you have there for more details)

  • I know you wanted to use toFixed, but unfortunately it does not allow a variable amount of decimals (unless you use the solution below - if (Number.isInteger(x)) { formata sem casas decimais } else { usa toFixed }). But I still think toLocaleString a better solution

  • It’s okay, I created an If and everything ended up being fine! I used isInteger to return true, and use toFixed only when it is false

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.