0

I have the following code

var number = 0618260587

JSON.stringify(number)

the stringified result is 618260587 , the first zero is automatically truncated.

I tried the following fix

if(number.length<8)
        {
        var book1 = "0" + number;
        alert(book1);

but it alerts undefined. I am not sure

1) Why the stringified data truncates the first zero 2) I thought javascript adds two variables irrespective of type

0

1 Answer 1

5

Leading zeroes are a display thing, and not normally part of numbers. There's an infinite number of invisible zeroes before/after every number, but they're not normally shown. If you want the leading zero, treat the number as a string:

var number = '0618260587';

As well, in most, numbers with a leading zero are treated as octal, not decimal. Bare leading zeroes can cause hard-to-track bugs because of this - it looks like a decimal to you, but it's some completely different number to the interpreters, eg..

0618260587 octal = 1616431 decimal
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for the warning about octals. In his case (at least on Firefox), it actually works as a decimal, because he has the digit 8. If you changed 8 to 6, it will become octal. Is this fallback to decimal in the presence of invalid octal digits spec'd somewhere?
Thank you for the explanation !! I would have done it , but I require the input to be a number and then stringify it . What is wrong with the fix I tried making?
@alex: you're not using numberin your fix. book is undefined, making the whole result undefined.
MarcB , apologies , I had changed the variable while putting the question up , I left that change , The problem still remains
if number is still an int, then it has no .length. You have to convert it to a string first. That means your if() is failing, since a number can never have a length, so it's doing if (undefined < 8).

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.