javascriptroundingprecision

Difference between toFixed() and toPrecision()?


I'm new to JavaScript and just discovered toFixed() and toPrecision() to round numbers. However, I can't figure out what the difference between the two is.

What is the difference between number.toFixed() and number.toPrecision()?


Solution

  • toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.

    Ref at w3schools: toFixed and toPrecision

    EDIT:
    I learned a while back that w3schools isn't exactly the best source, but I forgot about this answer until I saw kzh's, uh, "enthusiastic" comment. Here are additional refs from Mozilla Doc Center for toFixed() and for toPrecision(). Fortunately for all of us, MDC and w3schools agree with each other in this case.

    For completeness, I should mention that toFixed() is equivalent to toFixed(0) and toPrecision() just returns the original number with no formatting.

    And of course, the real source of truth is the JS specification, which in this case is https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.toprecision