5

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" ?

2
  • 000000 in numerics is just 0 for the interpreter, which the param holds 0. Use string quotes around it to "bypass" it Commented Apr 8, 2014 at 9:14
  • @KarelG I can't change the method which means I cant change the result. Commented Apr 8, 2014 at 9:27

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

1 Comment

I can't change the method which means I cant change the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.