Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Number
  6. toPrecision()

Number.prototype.toPrecision()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

ThetoPrecision() method ofNumber values returns a string representing this number to the specified number of significant digits.

Try it

function precise(x) {  return x.toPrecision(4);}console.log(precise(123.456));// Expected output: "123.5"console.log(precise(0.004));// Expected output: "0.004000"console.log(precise(1.23e5));// Expected output: "1.230e+5"

Syntax

js
toPrecision()toPrecision(precision)

Parameters

precisionOptional

An integer specifying the number of significant digits.

Return value

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 toprecision or less than -6. Has the same behavior asNumber.prototype.toString() if theprecision argument is omitted.

Exceptions

RangeError

Thrown ifprecision is not between1 and100 (inclusive).

TypeError

Thrown if this method is invoked on an object that is not aNumber.

Examples

UsingtoPrecision

js
// This number has exponent 0, so it will never use exponential notationlet 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 notationnum = 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 4num = 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 notationnum = 0.00000012345;console.log(num.toPrecision(1)); // '1e-7'console.log(num.toPrecision(10)); // '1.234500000e-7'

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp