A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-number-toprecision-method/ below:

JavaScript Number toPrecision() Method - GeeksforGeeks

JavaScript Number toPrecision() Method

Last Updated : 22 May, 2023

The JavaScript Number toPrecision( ) method in Javascript is used to format a number to a specific precision or length. If the formatted number requires more digits than the original number then decimals and nulls are also added to create the specified length. 

Syntax:

number.toPrecision(value)

Parameters: This method accepts a single optional parameter. 

Return Value: The toPrecision() method in JavaScript returns a string in which the number is formatted to the specified precision.

Below is an example of the Number toPrecision( ) Method.

Example 1: 

JavaScript
let num=213.45689;
console.log(num.toPrecision(3));        

Output:

213

Example 2: Passing no arguments in the toPrecision() method, If no arguments are passed to the toPrecision() method then the formatted number will be exactly the same as the input number. Though, it will be represented as a string rather than a number.

JavaScript
let num=213.45689;
console.log(num.toPrecision());        

Output:

213.45689

Example 3: Passing an argument in the toPrecision() method, If the length of precision passed to the toPrecision() method is smaller than the original number then the number is rounded off to that precision. 

JavaScript
let num=213.45689;
console.log(num.toPrecision(4));        

Output:

213.5

Example 4: Passing an argument that results in the addition of null in the output, If the length of precision passed to the toPrecision() method is greater than the original number then zeros are appended to the input number to meet the specified precision.

JavaScript
let num=213.45689;
console.log(num.toPrecision(12));

let num2 = 123;
console.log(num2.toPrecision(5));        

Output:

213.456890000
123.00

Note: If the precision specified is not between 1 and 100 (inclusive), it results in a RangeError.

Supported Browsers:

We have a complete list of Javascript Number Objects methods, to check those please go through this Javascript Number Complete reference article.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4