The JavaScript toFixed method will take a number and convert it to a string. You can also pass the toFixed() method a number and it will round the number to that many decimal places. If no number is given, it will just round the number to an Integer.
var num = 10.7354;
var numToString = num.toFixed();
console.log(numToString);
#Output
11
Let’s take a look at some more examples of the JavaScript toFixed() method.
The best way to learn how to use the JavaScript toFixed() method is to see it in action. Here are some more examples of it below.
var num = 2.485487;
var numToString1 = num.toFixed();
var numToString2 = num.toFixed(1);
var numToString3 = num.toFixed(2);
var numToString4 = num.toFixed(3);
var numToString5 = num.toFixed(8);
console.log(numToString1);
console.log(numToString2);
console.log(numToString3);
console.log(numToString4);
console.log(numToString5);
#Output
2
2.5
2.49
2.485
2.48548700
As you can see in our last example num.toFixed(8);
, if you pass a number that is larger than the number of decimal places in our number, zeros will be added to the end of the number.
Now let’s take an interactive look at the toFixed() method.
Using the JavaScript toFixed Method with User Input
Below we will provide code to let the user input two numbers. The first will be a number the user wants to be converted to a string. The second will be the number of decimal places to round to.
Here is our simple HTML setup:
Type a number you want converted to a string:
Type the number of decimal places you want the number rounded to:
Below is the JavaScript code which will take the user inputs using an onclick event along with the value property and use the toFixed() method on that user input and update the results below using the textContent property.
Here is our JavaScript code to do this:
function convertNumtoString() {
var roundedNumber;
//Get the number the user entered
var userNum = Number(document.getElementById("userVal1").value);
//Get the number of decimal places the user entered
var userNum2 = Number(document.getElementById("userVal2").value);
//Convert Number to string to the decimal places entered
var numToString = userNum.toFixed(userNum2);
//Show the number to the user
document.getElementById("results").textContent = numToString;
};
The final code and output for this example are below:
Code Output:
Type a number you want converted to a string:
Type the number of decimal places you want the number rounded to:
Full Code:
Type a number you want converted to a string:
Type the number of decimal places you want the number rounded to:
Hopefully this article has been useful in helping you understand how to use the JavaScript toFixed method.