admin管理员组

文章数量:1344609

I have a problem, I build a very simple javascript search for postal codes. I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.

value >= splitZips[0] && value <= splitZips[1]

But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.

Any idea how to fix this?

I have a problem, I build a very simple javascript search for postal codes. I am using JS Numbers because I want to check if the passed number (search term) is less||equal or more||equal to the max and min.

value >= splitZips[0] && value <= splitZips[1]

But the Javascript Number var type deletes leading 0, which is a problem because I have postal codes like 01075 and also postal codes like 8430. So it can not find the small 4 digit codes.

Any idea how to fix this?

Share Improve this question asked Dec 19, 2011 at 9:03 Lukas OppermannLukas Oppermann 2,9288 gold badges48 silver badges64 bronze badges 1
  • 1 What do you expect to get when paring "0123" with "123"? When treated as numbers they are equal, but for your purpose they clearly aren't. Perhaps you can pare them as strings, as "0123" < "123" is valid in javascript and will pare based on the characters in the string. – AVee Commented Dec 19, 2011 at 9:12
Add a ment  | 

3 Answers 3

Reset to default 7

Represent them as a String. Outside of strict mode, a leading zero denotes an octal number otherwise.

Also, why would a leading zero have any significance when calculating numbers? Just use parseInt(num, 10) if you need to.

Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical parison convert to number at the time. The easiest way to convert is with the unary plus operator:

var strPC = "01745",
    numPC = +strPC;

alert(numPC === +"01745"); // true

+value >= +splitZips[0] && +value <= +splitZips[1];
// etc.

Before you start paring you might want to ensure the entered value actually is numeric - an easy way to be sure it is a four or five digit code with or without leading zeros is with a regex:

/^\d{4,5}$/.test(searchTerm)       // returns true or false

Instead a parseInt you could use type casting :)

"0123">"122" // false
+"0123">"122" // true  | that  means: 123>"122" 

Btw, what more you can use a each of bitwise operators :

 ~~"0123"   
 "0123"|0  
 "0123"&"0123" 
 "0123">>0
 "0123"<<0 

With the same effect :)

本文标签: JavaScript Number preserve leading 0Stack Overflow