tags:

views:

76

answers:

3

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

+4  A: 

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.

Tom
Nice example. ` `
Lord Torgamus
Apparently not nice enough for the accepted answer :-)
Tom
+1  A: 

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.

Lord Torgamus
+1  A: 

Under certain circumstances, toPrecision() will return exponential notation, whereas toFixed() will not.

Robusto
Actually, `toExponential()` is a [separate function](http://www.w3schools.com/jsref/jsref_toexponential.asp).
Lord Torgamus
@Lord Torgamus: According to my copy of *Javascript: The Definitive Guide*, toPrecision(precision) will use fixed-point notation if the *precision* arg is large enough to include all the digits of the integer part of the number. Otherwise, exponential notation is used.
Robusto
@Robusto, I ran a test and you are correct. +1, I didn't know about that behavior before.
Lord Torgamus