Number.prototype.toPrecision()

Number 值的 toPrecision() 方法返回一个表示此数字的字符串,以指定有效位数表示。

¥The toPrecision() method of Number values returns a string representing this number to the specified number of significant digits.

Try it

语法

¥Syntax

js
toPrecision()
toPrecision(precision)

参数

¥Parameters

precision Optional

指定有效位数的整数。

TypeError

如果在不是 Number 的对象上调用此方法,则会抛出该异常。

返回值

¥Return value

表示给定数字的字符串,使用给定数量的有效数字。如果指数大于或等于 precision 或小于 -6,则使用科学计数法。如果省略 precision 参数,则具有与 Number.prototype.toString() 相同的行为。

¥A string representing the given number, using the given number of significant digits. Scientific notation is used if the exponent is greater than or equal to precision or less than -6. Has the same behavior as Number.prototype.toString() if the precision argument is omitted.

例外情况

¥Exceptions

RangeError

如果 precision 不在 1100(含)之间,则抛出该异常。

示例

¥Examples

使用 toPrecision

¥Using toPrecision

js
// This number has exponent 0, so it will never use exponential notation
let num = 5.123456;

console.log(num.toPrecision()); // '5.123456'
console.log(num.toPrecision(5)); // '5.1235'
console.log(num.toPrecision(2)); // '5.1'
console.log(num.toPrecision(1)); // '5'

// This number has exponent -4, so it will never use exponential notation
num = 0.000123;

console.log(num.toPrecision()); // '0.000123'
console.log(num.toPrecision(5)); // '0.00012300'
console.log(num.toPrecision(2)); // '0.00012'
console.log(num.toPrecision(1)); // '0.0001'

// This number has exponent 3, so it will use exponential notation if precision is less than 4
num = 1234.5;
console.log(num.toPrecision(1)); // '1e+3'
console.log(num.toPrecision(2)); // '1.2e+3'
console.log(num.toPrecision(6)); // '1234.50'

// This number has exponent -7, so it will always use exponential notation
num = 0.00000012345;
console.log(num.toPrecision(1)); // '1e-7'
console.log(num.toPrecision(10)); // '1.234500000e-7'

规范

Specification
ECMAScript Language Specification
# sec-number.prototype.toprecision

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看