The toPrecision() method returns a string representing the Number object to the specified precision.
numObj.toPrecision([precision])
precisionA string representing a Number object in fixed-point or exponential notation rounded to precision significant digits. See the discussion of rounding in the description of the numObj.toFixed() method, which also applies to toPrecision().
If the precision argument is omitted, behaves as numObj.toString(). If the precision argument is a non-integer value, it is rounded to the nearest integer.
precison is not between 1 and 100 (inclusive), a RangeError is thrown. Implementations are allowed to support larger and smaller values as well. ECMA-262 only requires a precision of up to 21 significant digits.toPrecisionvar numObj = 5.123456; console.log(numObj.toPrecision()); // logs 5.123456 console.log(numObj.toPrecision(5)); // logs 5.1235 console.log(numObj.toPrecision(2)); // logs 5.1 console.log(numObj.toPrecision(1)); // logs 5 // note that exponential notation might be returned in some circumstances console.log((1234.5).toPrecision(2)); // logs 1.2e+3
Created by Mozilla Contributors, license: CC-BY-SA 2.5