JavaScript Number preserve leading 0

前端 未结 3 791
盖世英雄少女心
盖世英雄少女心 2020-12-02 02:53

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 o

相关标签:
3条回答
  • 2020-12-02 03:01

    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
    
    0 讨论(0)
  • 2020-12-02 03:11

    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.

    0 讨论(0)
  • 2020-12-02 03:15

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

    0 讨论(0)
提交回复
热议问题