Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Add '0' before single digit numbers jQuery?

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #147312
    Rugg
    Participant

    Hello,

    I am working on a simple script to increase a number value by one digit. Everything seems to function as planed, but I can’t seem to add a ‘0’ before single digit numbers < 10.

    Could someone please suggest a method or approach to solve this please? Thank You and good day.

    Code Sample:
    http://jsfiddle.net/7nVbf/

    #147327
    Paulie_D
    Member
    #147330
    Kuzyo
    Participant

    Hi, i made in this way:

    $('.box').click(function () {
    
        $(this).text(function (i, n) {
            var result = Number(n) + 1;
            if ( result < 10 ) {
                return "0" + result;
            } else {
                return result;
            }
        });
    
    });
    

    @Rugg where I can read about this variant of counting :

    $(this).text(function (i, n) {
    
            return Number(n) + 1;
    
        });
    

    Thanks.

    #147355
    dgriesel
    Participant

    see here: http://jsfiddle.net/Sf62b/1/

    The trick is that you have to return a string, because numbers don’t have leading zeros:

    return (n < 9 ? "0" : "") + (n + 1);
    

    The first part returns “0” if the number is less than 9, the second part appends the number, increased by one. The result is a string (string + number -> string). Note: I compare n with 9, because n+1 doesn’t need a trailing zero when n is 9.

    However, on the next click, n contains “01”, so the above code would result in “0011”, because “01” < 10 and “001” + 1 = “0011”… loose type weirdness. So first, you have to cast n back to a number, like this

    n = new Number(n);
    

    or even shorter

    n = +n
    

    You could also compress all that into one statement:

    return ((n = +n+1) < 10 ? "0" : "") + n;
    
Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.