user3218006
user3218006

Reputation:

Is it possible to add extra zero at front of an input if the integer value received is three digit

Hi I have an input field that is transmitting integer...

However when I do

parseInt($('#postCode').val());

I am losing the first digit if the value received is like 0880 . I want to transmit all the four digits but as an integer.. is that possible?Basically I want to make sure that if

parseInt($('#postCode').val()); 

is of three digits that just add one extra 0 at the front.

Upvotes: 0

Views: 478

Answers (3)

Sriram
Sriram

Reputation: 2999

You are very close to the answer. Before you do parseInt, you can add a check whether it's a number or not. Use [$.isNumeric()][1] to check for a numeric type and then if it returns 3 digits, simply add 0 to your $("#postCode").val()

Upvotes: 0

mtripp100
mtripp100

Reputation: 241

Be very careful - in some older browsers (pre ECMAScript 5), a number starting with a 0 is interpreted as an octal number by parseInt, which is almost certainly not what you want.

Why do you want to store it as an integer? I would argue that a postcode/zip-code does not semantically represent a number, and so a string is more appropriate.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075537

If you want the leading zero, then it has to be a string. Just don't call parseInt at all. With most post codes I've seen, they are a series of digits (or letters and digits), but they aren't numbers.

If you want to use parseInt to make sure it's a number, you can add back the leading zero; but again, that will be a string, not a number.

E.g.:

var str = String(parseInt($("#postCode").val(), 10));
while (str.length < 4) {
    str = "0" + str;
}

(Note the second argument to parseInt; if you're using parseInt, you almost always want to tell it what radix — number base — to use.)

Upvotes: 1

Related Questions