Hello
I'm new to javascript. just discovered toFixed & toPrecision to round numbers but i can't figure what is the diff between both?
thanks
Hello
I'm new to javascript. just discovered toFixed & toPrecision to round numbers but i can't figure what is the diff between both?
thanks
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
EDIT: Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford.
toFixed(n) provides n length after the decimal point; toPrecision(x) provides x total length.
Ref at w3schools: toFixed and toPrecision
Edit:
For completeness, I should mention that toFixed() is equivalent to toFixed(0) and toPrecision() just returns the original number with no formatting.
Under certain circumstances, toPrecision() will return exponential notation, whereas toFixed() will not.