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 just0
for the interpreter, which theparam
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
3 Answers
Reset to default 1If 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
版权声明:本文标题:JavaScript convert int to String - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744967908a2635060.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论