admin管理员组

文章数量:1406177

I'm facing strange convertion in JavaScript:

    function getFromDatabase(){
      //the result may be gotten from database or some plex methods and CANT be changed!
      return 000000;
    }

    var param = getFromDatabase();
    alert(param);// -> 0        
    alert(param.toString());// -> 0         
    alert("" +param + "");// -> 0       

How can I get 000000 or "000000" ?

I'm facing strange convertion in JavaScript:

    function getFromDatabase(){
      //the result may be gotten from database or some plex methods and CANT be changed!
      return 000000;
    }

    var param = getFromDatabase();
    alert(param);// -> 0        
    alert(param.toString());// -> 0         
    alert("" +param + "");// -> 0       

How can I get 000000 or "000000" ?

Share Improve this question edited Apr 8, 2014 at 9:36 Sam Su asked Apr 8, 2014 at 9:10 Sam SuSam Su 6,8628 gold badges42 silver badges83 bronze badges 2
  • 000000 in numerics is just 0 for the interpreter, which the param holds 0. Use string quotes around it to "bypass" it – KarelG Commented Apr 8, 2014 at 9:14
  • @KarelG I can't change the method which means I cant change the result. – Sam Su Commented Apr 8, 2014 at 9:27
Add a ment  | 

3 Answers 3

Reset to default 1

If you want to differentiate 000000 from 0, you can't. 000000 is "converted" to 0 before leaving the function.

If you want to print leading zeros, try something like

function intToLeadingZerosString(myint){
  var s= myint.toString(10);
  return Array( 6-s.length+1 ).join("0") + s;
}
alert(intToLeadingZerosString(param));

Or:

Number.prototype.toStringLeading = function() {
   var s = this.toString(10);
   return Array( (arguments.length?arguments[0]:6)-s.length+1 ).join("0") + s;
};
alert(param.toStringLeading(6));
alert(param.toStringLeading());

why don't you convert it to string while returning it? because, value sent by return statement is will be returned by concept of "copy by value". Also it is assigned to param by copying it (i.e. copy by value). So, 000000 converts to just 0. After that, converting it to String will be "0".

    function getFromDatabase(){
      return '000000'; 
    }

    var param = getFromDatabase();      
    alert(param);// -> 000000         
    alert(isNaN(param)?"":parseInt(param));// -> 0

Return as string and later convert it to int if required. This will be the best way of handling your scenario.

Because your function returns 'int' value. Try to change on return '000000';

本文标签: JavaScript convert int to StringStack Overflow