2

I try to convert a number with leading zero. JavaScript interpret the number with leading zero as octal number. But I would like to convert the number to string as decimal number and preserve the leading zero. Any idea?

<!DOCTYPE html>
 <html>
 <body>

<p>Click the button to display the formatted number.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
    function myFunction() {
    var num = 015;

    var n = Number(num).toString();
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>
CK8
  • 239
  • 4
  • 20
  • 2
    a numeric literal with a leading zero and no digits greater than 7 will always be interpreted as an octal ... so don't do that with literals – Jaromanda X Dec 29 '16 at 02:26
  • Thanks, @Jaromanda. I have never known that. – vothaison Dec 29 '16 at 02:39
  • The num field is a input field, sometime there is leading zero in the field. – CK8 Dec 29 '16 at 02:40
  • no, in the code you posted, the num **var** is an octal literal. Perhaps you should've posted the actual code, and explained that "sometimes the input field has a leading zero" - because you'd want to parseInt(stringValue, 10) to ensure the number is considered to be decimal rather than octal – Jaromanda X Dec 29 '16 at 02:44
  • For padding a number with leading zeros, see [*Pad a number with leading zeros in JavaScript*](http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript). – RobG Dec 29 '16 at 02:44

2 Answers2

1

try below code

function pad(num, size) {
        var s = num + "";
        while (s.length < size) s = "0" + s;
        return s;
    }
    document.getElementById("demo").innerHTML = pad(15, 4);

output: 0015

0

The parseInt() and parseFloat() functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.

+"42"; // 42
+"010"; // 10
+"0x10"; // 16

a = "0042";
alert(typeof +a); // number
alert(+a); // 42

Joe Yichong
  • 615
  • 4
  • 8