Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a leading zero if a number is less than 10 [duplicate]

Possible Duplicate:
JavaScript equivalent to printf/string.format
How can I create a Zerofilled value using JavaScript?

I have a number in a variable:

var number = 5; 

I need that number to be output as 05:

alert(number); // I want the alert to display 05, rather than 5. 

How can I do this?

I could manually check the number and add a 0 to it as a string, but I was hoping there's a JS function that would do it?

like image 388
Nicekiwi Avatar asked Nov 11 '11 04:11

Nicekiwi


People also ask

How do you add a leading zero when a number is less than 10?

The safest way is probably to only add zeroes when the length of the column is 1 character: UPDATE Table SET MyCol = '0' + MyCol WHERE LEN(MyCol) = 1; This will cover all numbers under 10 and also ignore any that already have a leading 0.

What is the rule for leading zeros?

1) Leading zeroes shall be suppressed, although a single zero before a decimal point is allowed. 2) Significant zeroes shall not be suppressed; when a single zero is significant, it may be used. 3) Do not include Trailing zeroes after the decimal point unless they are needed to indicate precision.

What does a leading zero look like?

A leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, James Bond's famous identifier, 007, has two leading zeros. When leading zeros occupy the most significant digits of an integer, they could be left blank or omitted for the same numeric value.


2 Answers

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {     return (n < 10) ? ("0" + n) : n; } 

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

console.log(String(5).padStart(2, '0'));
like image 175
Chris Fulstow Avatar answered Sep 19 '22 17:09

Chris Fulstow


Try this

function pad (str, max) {   return str.length < max ? pad("0" + str, max) : str; }  alert(pad("5", 2)); 

Example

http://jsfiddle.net/

Or

var number = 5; var i; if (number < 10) {     alert("0"+number); } 

Example

http://jsfiddle.net/

like image 26
Wazy Avatar answered Sep 22 '22 17:09

Wazy