toPrecision()
method returns a string representing the
Number
object to the specified precision.
numObj.toPrecision([precision])
precision
可选
An integer specifying the number of significant digits.
A 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
Number.prototype.toFixed()
method, which also applies to
toPrecision()
.
若
precision
argument is omitted, behaves as
Number.prototype.toString()
。若
precision
argument is a non-integer value, it is rounded to the nearest integer.
RangeError
precision
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.
toPrecision
let 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' numObj = 0.000123 console.log(numObj.toPrecision()) // logs '0.000123' console.log(numObj.toPrecision(5)) // logs '0.00012300' console.log(numObj.toPrecision(2)) // logs '0.00012' console.log(numObj.toPrecision(1)) // logs '0.0001' // note that exponential notation might be returned in some circumstances console.log((1234.5).toPrecision(2)) // logs '1.2e+3'
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'Number.prototype.toPrecision' in that specification. |
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
更新 GitHub 上的兼容性数据| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
toPrecision
|
Chrome 1 | Edge 12 | Firefox 1 | IE 5.5 | Opera 7 | Safari 2 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |
完整支持
Number
Number.isFinite()
Number.isInteger()
Number.isNaN()
Number.isSafeInteger()
Number.parseFloat()
Number.parseInt()
Number.prototype.toExponential()
Number.prototype.toFixed()
Number.prototype.toLocaleString()
Number.prototype.toPrecision()
Number.prototype.toSource()
Number.prototype.toString()
Number.prototype.valueOf()
Function
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()