Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js jQuery, always have a number display at least two digits 00

I'm using the following to add one to number:

<div id="count">00</div>
<div id="count">03</div>
<div id="count">08</div>
<div id="count">12</div>

$('#count').text(function(i,txt) { return parseInt(txt, 10) + 1; });

I always want there two be 2 places, 00 even if the number is under 10. How can I get the func above, with JS, to always return the 2 00 places? So if the number computes to 3, it injects 03 into #count?

Thanks

like image 218
AnApprentice Avatar asked Nov 23 '10 19:11

AnApprentice


People also ask

Why is 0 not a number in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.

How do you display a number in JavaScript?

In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object). The valueOf() method is used internally in JavaScript to convert Number objects to primitive values. There is no reason to use it in your code. All JavaScript data types have a valueOf() and a toString() method.


2 Answers

$('#count').text(function(i,txt) { var c = parseInt(txt, 10) + 1; return (c<10) ? "0"+c : c; });

EDIT: But having multiple elements with the same ID is gonna cause problems somewhere.

like image 67
Niet the Dark Absol Avatar answered Oct 22 '22 14:10

Niet the Dark Absol


Here's a little different approach from the others. Doesn't use a conditional operator.

$('#count').text(function(i, txt) {
    return ("0" + (+txt + 1)).slice(-2);
});

It just assumes it will need the extra 0, then returns a slice of the last two characters in the string.

like image 20
user113716 Avatar answered Oct 22 '22 14:10

user113716