JavaScript convert int to String - Stack Overflow

I'm facing strange convertion in JavaScript:function getFromDatabase(){the result may be gotten

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';

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744967908a4603793.html

相关推荐

  • JavaScript convert int to String - Stack Overflow

    I'm facing strange convertion in JavaScript:function getFromDatabase(){the result may be gotten

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信