Unable to retain leading zeros in javascript

后端 未结 2 563
遇见更好的自我
遇见更好的自我 2021-01-15 08:06

I have

var x = \"0100\";

parseInt(x); // returns 100;

Is there a way I can retain the leading 0s and yet convert to number in Javascript<

相关标签:
2条回答
  • 2021-01-15 08:20

    No.

    Numbers don't have leading zeroes; that's a display issue, not a matter of a number's internal representation.

    To display the number with leading zeroes, see here.

    0 讨论(0)
  • 2021-01-15 08:23

    Unfortunately it's not possible but I have a solution that can help you, is to define a class from where you can get the value as integer and when you call the toString method it returns the value with leading zeros

    function Num ()
    {
        this.value = arguments[0];
        this.val = this.valueOf = function () 
        {
           return parseInt(this.value);
        }
        this.toString = function()
        {
           return this.value;
        }
    }
    

    Now what you can do is to define a new number like this :

    var x = new Num("00011");
    x.val() // returns 11
    x.toString() // returns "00011"
    
    0 讨论(0)
提交回复
热议问题