Home » JavaScript

Number toPrecision() Method with Example in JavaScript

JavaScript Number toPrecision() Method: Here, we are going to learn about the toPrecision() method with example.
Submitted by IncludeHelp, on February 20, 2019

Number toPrecision() Method

toPrecision() method is a method of Number class, it is used to convert a number to a specified length, including the decimal point (if target length is short).

Syntax:

    Number.toPrecision(n);

Here, n is used to define the length of the number.

Examples:

    Input: 10
    num = 123.456

    Function call       Output
    num.toPrecision(8)  123.45600
    num.toPrecision(5)  123.45
    num.toPrecision(4)  123.4

Code:

<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
	var num = 123.456;	
	var res1 = num.toPrecision(3);
	var res2 = num.toPrecision(4);
	var res3 = num.toPrecision(5);
	var res4 = num.toPrecision(6);
	var res5 = num.toPrecision(7);
	var res6 = num.toPrecision(8);
	
	document.write("res1 = " + res1 + "<br>");
	document.write("res2 = " + res2 + "<br>");
	document.write("res3 = " + res3 + "<br>");
	document.write("res4 = " + res4 + "<br>");
	document.write("res7 = " + res5 + "<br>");
	document.write("res6 = " + res6 + "<br>");	
</script>
</body>
</html>

Output

res1 = 123
res2 = 123.5
res3 = 123.46
res4 = 123.456
res7 = 123.4560
res6 = 123.45600





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.