myNumber.toPrecision( precision ) in ECMAScript 262
Return the number as a string in either in fixed or exponential notation, with the specified number of digits.
Arguments
name | type | description |
---|---|---|
precision | Number | The amount of precision which< |
- Return Type
- String
Description
By default, the specs require precision
to be between 1 and 21 (inclusive). If it is outside this range, an error will be generated. However, specific implementations may extend this range further.
If precision
is omitted, toString()
is called instead.
var precision = [1,2,3,4];
var numbers = [ 0 , 1.5 , 873 , 10230];
var msg="";
for (var i=0,len=numbers.length;i<en;i++){
var n = numbers[i];
for (var j=0,len2=precision.length;j<len2;j++){
var digits = precision[j];
msg += "("+n+").toPrecision("+digits+") is '"+n.toPrecision(digits)+"'\n";
}
}
/**************************
msg is
(0).toPrecision(1) is '0'
(0).toPrecision(2) is '0.0'
(0).toPrecision(3) is '0.00'
(0).toPrecision(4) is '0.000'
(1.5).toPrecision(1) is '2'
(1.5).toPrecision(2) is '1.5'
(1.5).toPrecision(3) is '1.50'
(1.5).toPrecision(4) is '1.500'
(873).toPrecision(1) is '9e+2'
(873).toPrecision(2) is '8.7e+2'
(873).toPrecision(3) is '873'
(873).toPrecision(4) is '873.0'
(10230).toPrecision(1) is '1e+4'
(10230).toPrecision(2) is '1.0e+4'
(10230).toPrecision(3) is '1.02e+4'
(10230).toPrecision(4) is '1.023e+4'
**************************/