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.

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
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

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: