This content originally appeared on Go Make Things and was authored by Go Make Things
Yesterday, we looked at a few ways to convert strings to numbers. Today, we’re looking at how to convert numbers to strings with JavaScript.
Let’s dig in!
The Number.toFixed()
method
You can use the Number.toFixed()
method to format a number to a fixed number of decimal places. Pass in the number of decimal places as an argument.
It returns a string.
let pi = 3.14159;
let eleven = 11;
// returns 3.14
pi.toFixed(2);
// returns 11.000
eleven.toFixed(3);
In yesterday’s article, I noted:
You can also pass existing numbers into the parseFloat() method, though it won’t add decimals to an integer. It gets returned out as-is.
You can combine parseFloat()
with Number.toFixed()
to add decimals.
// returns 42.00
let answer = parseFloat('42').toFixed(2);
The Number.toString()
method
Convert a number to a string.
let pi = 3.14;
let eleven = 11;
// returns "3.14"
pi.toString();
// returns "11"
eleven.toString();
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-01-26T15:30:00+00:00) Converting numbers to strings with vanilla JavaScript. Retrieved from https://www.scien.cx/2022/01/26/converting-numbers-to-strings-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.