How do you restrict a number result to 4 decimal places?

I am working on an equation that goes:
gpm = rpm x displacement / 231 =

I got the code correct, but the results can throw a number with 8 decimal places for example… So, how can I limit the result to a maximum of 4 decimal places?

The .onclick funtion I have is this:

equals2.onclick = function () {
    const rpmValue = Number(rpm2.value)
  const displacementValue = Number(displacement2.value)
    const result2 = gpm(rpmValue, displacementValue)
  gpmresult.innerHTML = result2 + " gpm"

If you want to see the entire code is here:

you can’t limit the number of decimal places of a number, but you can convert it to a string keeping only a certain number of decimal places, like with toFixed


Thank you for your info!

This is why I’m glad we have sane people like @ilenia here, they keep me balanced lol

toFixed() is the quickest and cleanest way, but being an overthinker, i had to think your question through.

  1. We want a number of a certain precision (for example, four decimal places, which is ten-thousandths or 10^-4).
  2. We can round a number, but only to the nearest integer.
  3. We would need to move the decimal to the right (in this case, by multiplying by 10,000), round that, and shift the decimal point back (by dividing by 10,000)!

Y’know what? .toFixed() is ** brilliant**! Rofl

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.