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()
?
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()
?
I think this is best answered with an example.
Let's say you have the following data:
You want to display each of these products with the title and formatted price. Let's try using
toPrecision
first:Looks good, so you might think this will work for the other products as well:
Not so good. We can fix this by changing the number of significant digits for each product, but if we're iterating over the array of products that could be tricky. Let's use
toFixed
instead:This produces what you expected. There is no guess work involved, and there is no rounding.
For example , we consider the variable a as, var a = 123.45 a.toPrecision(6) The output is 123.450 a.toFixed(6) The output is like 123.450000 // 6 digits after decimal point
toFixed(n)
providesn
length after the decimal point;toPrecision(x)
providesx
total length.Ref at w3schools: toFixed and toPrecision
For completeness, I should mention that
toFixed()
is equivalent totoFixed(0)
andtoPrecision()
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.
Furthermore,
toPrecision
will yield scientific notation if there are more integer digits in the number than the specified precision.EDIT: Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford.
Under certain circumstances,
toPrecision()
will return exponential notation, whereastoFixed()
will not.Examples speak clearly: