3

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?

Lukas Oppermann
  • 2,918
  • 6
  • 47
  • 62
  • 1
    What do you expect to get when comparing "0123" with "123"? When treated as numbers they are equal, but for your purpose they clearly aren't. Perhaps you can compare them as strings, as `"0123" < "123"` is valid in javascript and will compare based on the characters in the string. – AVee Dec 19 '11 at 09:12

3 Answers3

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.

Vemonus
  • 868
  • 1
  • 16
  • 28
alex
  • 479,566
  • 201
  • 878
  • 984
2

Store and display the postcodes as strings, thus retaining the leading zeros. If you need to make a numerical comparison 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 comparing 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
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

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 :)

abuduba
  • 4,986
  • 7
  • 26
  • 43