Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript convert int to String

I'm facing strange convertion in JavaScript:

    function getFromDatabase(){
      //the result may be gotten from database or some complex 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" ?

like image 697
Sam Su Avatar asked Nov 11 '22 09:11

Sam Su


1 Answers

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());
like image 91
Mathias Avatar answered Nov 14 '22 21:11

Mathias