Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a Number, Exactly Two in Length?

Tags:

javascript

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
...

like image 379
John R Avatar asked Apr 24 '11 23:04

John R


People also ask

How to format a number to 2 decimal places in JavaScript?

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.

What is length of a number?

The length of a number in base is the number of digits in the base- numeral for , given by the formula.

How to set How many decimal places in JavaScript?

JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

How do you format numbers in JavaScript?

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.


2 Answers

Update

This answer was written in 2011. See liubiantao's answer for the 2021 version.

Original

function pad(d) {     return (d < 10) ? '0' + d.toString() : d.toString(); }  pad(1);  // 01 pad(9);  // 09 pad(10); // 10 
like image 143
Chris Nielsen Avatar answered Oct 11 '22 02:10

Chris Nielsen


String("0" + x).slice(-2); 

where x is your number.

like image 33
Jigish Chawda Avatar answered Oct 11 '22 03:10

Jigish Chawda