Difference between toFixed() and toPrecision()?
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 fortoFixed()
and fortoPrecision()
. 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.
I believe that the former gives you a fixed number of decimal places, whereas the latter gives you a fixed number of significant digits.
Math.PI.toFixed(2); // "3.14"Math.PI.toPrecision(2); // "3.1"
Furthermore, toPrecision
will yield scientific notation if there are more integer digits in the number than the specified precision.
(Math.PI * 10).toPrecision(2); // "31"(Math.PI * 100).toPrecision(2); // "3.1e+2"
EDIT:Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford.
Examples speak clearly:
var A = 123.456789;A.toFixed() // 123A.toFixed(0) // 123A.toFixed(1) // 123.5 round up lastA.toFixed(2) // 123.46 round up lastA.toFixed(3) // 123.457 round up lastA.toFixed(4) // 123.4568 round up lastA.toFixed(5) // 123.45679 round up lastA.toFixed(6) // 123.456789A.toFixed(7) // 123.4567890A.toFixed(8) // 123.45678900A.toFixed(9) // 123.456789000A.toFixed(10) // 123.4567890000A.toFixed(11) // 123.45678900000A.toPrecision() // 123.456789 A.toPrecision(0) // --- ERROR --- A.toPrecision(1) // 1e+2A.toPrecision(2) // 1.2e+2A.toPrecision(3) // 123A.toPrecision(4) // 123.5 round up lastA.toPrecision(5) // 123.46 round up lastA.toPrecision(6) // 123.457 round up lastA.toPrecision(7) // 123.4568 round up lastA.toPrecision(8) // 123.45679 round up lastA.toPrecision(9) // 123.456789A.toPrecision(10) // 123.4567890A.toPrecision(11) // 123.45678900