I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:
01
02
03
...
09
10
11
12
...
Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.
The length of a number in base is the number of digits in the base- numeral for , given by the formula.
JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.
JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.
This answer was written in 2011. See liubiantao's answer for the 2021 version.
function pad(d) { return (d < 10) ? '0' + d.toString() : d.toString(); } pad(1); // 01 pad(9); // 09 pad(10); // 10
String("0" + x).slice(-2);
where x
is your number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With