Home » JavaScript

Number toFixed() Method with Example in JavaScript

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

Number toFixed() Method

toFixed() method is a method of Number class, it is used to convert a number to the string with a given fixed number of decimals.

Syntax:

    Number.toFixed([n]);

Here, n is an optional parameter, it is used to define the number of decimals, its default value is 0.

Examples:

    Input: 10
    num = 123.456

    Function call   Output
    num.toFixed()   123
    num.toFixed(0)  123
    num.toFixed(2)  123.45
    num.toFixed(6)  123.45600

Code:

<html>
<head>
<title>JavaScipt Example</title>
</head>
<body>
<script>
	var num = 123.456;
	
	var res1 = num.toFixed();
	var res2 = num.toFixed(0);
	var res3 = num.toFixed(2);
	var res4 = num.toFixed(4);
	var res5 = num.toFixed(6);
		
	document.write("res1 = " + res1 + "<br>");
	document.write("res2 = " + res2 + "<br>");
	document.write("res3 = " + res3 + "<br>");
	document.write("res4 = " + res4 + "<br>");
	document.write("res5 = " + res5 + "<br>");
	
</script>
</body>
</html>

Output

res1 = 123
res2 = 123
res3 = 123.46
res4 = 123.4560
res5 = 123.456000





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.