What happens when a number has a leading zero? - javascript

I've been trying to debug a problem today and I finally found out what the problem is. For some reason, when a number has a leading zero JavaScript does something really weird.
Example:
alert(132);
alert(0132);
var test = 0132;
alert(test);
JSFiddle: http://jsfiddle.net/U8sFu/3/
The first popup says "132," the second "90," and the third says "90."
My question is, why does the number 0132 become the number 90? This is really baffling to me!

A number with a leading 0 is parsed as an octal literal, which is in base 8.

Related

5.constructor.name - SyntaxError [duplicate]

For example,
1.toFixed(2) // Uncaught SyntaxError: Invalid or unexpected token
(1).toFixed(2) // "1.00"
let num = 1
num.toFixed(2) // "1.00"
At the same time, you don't have to wrap parenthesis around strings to call methods on them
'yo'.repeat(3) // "yoyoyo"
What is the rule at play here and where else does it apply? Guessing it has something to do with the dot being misinterpreted as a decimal for numbers?
Because the interpreter is looking for more digits (decimal values), not keywords or methods.
As others have stated, JavaScript is looking for more numbers after the decimal point. It thinks you are trying to type a float like 1.2 and it doesn't like that t there, it's not a number.
Interestingly, you can do this without parenthesis or making variable by using 2 decimal points. Like this: 1..toFixed(2). I guess you can also do 1.0.toFixed(2) if you want.
When using a variable, Javascript is confident that you're not going to add decimals after the point.
When not using a variable, Javascript thinks that you are going to add decimals after the point.
When you wrap your number with parenthesis, you say that the number is finished, and everything is fine again.
You can also use .. if you don't like parenthesis. The first one for decimals, the second one to call the method.
let num = 1;
console.log(num.toFixed(2));
// console.log(1.toFixed(2)); // ERROR
console.log((1).toFixed(2));
console.log(1..toFixed(2));

Adding a whole number and a decimal in Javascript results in removal of the decimal?

I'm sure this is simple, but in my javascript code, I have two numbers. One contains a decimal, and the other doesn't, and I add them together (ie. 7.5 + 5), I am getting a result with NO decimal value.
Do I need to cast each number variable as a double? I know that all numbers are doubles in javascript - which is why I do not understand this behavior...
For instance, I have var answer = week1 + week2;. Does this make sense?
Thanks in advance!
I am sorry for wasting time - turns out I was using parseInt instead of parseFloat to gather the "week" values I spoke about.
Can someone please close this question or delete it? Before the shame consumes me?

JS what happens to my number [duplicate]

I've been trying to debug a problem today and I finally found out what the problem is. For some reason, when a number has a leading zero JavaScript does something really weird.
Example:
alert(132);
alert(0132);
var test = 0132;
alert(test);
JSFiddle: http://jsfiddle.net/U8sFu/3/
The first popup says "132," the second "90," and the third says "90."
My question is, why does the number 0132 become the number 90? This is really baffling to me!
A number with a leading 0 is parsed as an octal literal, which is in base 8.

toFixed hanging my code

I am taking practice exercises and ran into this issue.
This problem asks:
“Prompt for a number greater than 1 and to 4 decimal places. Format
and write the number to the page displaying with only 2 digits past
the decimal point using the toFixed() method. (e.g. 12.35, not
12.3453)
Since this method is very new, it doesn't work in older browsers. See
if you can get only 2 digits past the decimal point to show without
using toFixed().”
I found the answer to the hard part through the archives here, Math.round(n*100)/100. Thanks for that. But when I tried the “easy” way, I get nothing. My work is at jsFiddle, but in a nutshell:
var num = prompt("Give me a number greater than one, with 4 decimal places.");
var num2 = prompt("Great! Do one more, please!");
num = Math.round(num*100)/100;
num2 = num2.toFixed(2);
alert(num);
alert(num2);
The exercise did not ask for a second number, but I wanted to use both methods in separate incidences. When I run this it does not alert anything. I know that it is hanging at the toFixed statement, because when I comment it out it alerts both as expected, num1 at 2 decimal places, and num2 as it was prompted (i.e. 1.2345).
So here is what I have done so far:
Mozilla’s developer page shows this format: n.toFixed(1);// Returns "12345.7": note rounding
Seems exactly what I am doing.
I copied and pasted all of it in my Sublime, making sure that I called the .js file just before the closing body tag, to make sure it wasn’t some loading problem I don’t understand.
Plus all sorts of little tweaking.
Sorry to keep asking these questions, but since I am self-study, I have where else to go!
You need to use parseFloat. Using the function will convert the string to a float type variable, allowing for the toFixed function to work properly.
num2 = parseFloat(num2).toFixed(2);

Javascript alert number starting with 0

I have a button where in the code behind I add a onclick and I pass a unique ID which will be passed to the js function. The id starts with a 0.
It wasn't working and eventually I figured out that the number, id, it was passing was wrong...
Ie. see this: js fiddle
It works with a ' at the start and end of the number. Just wondering why 013 turns to 11. I did some googling and couldn't find anything...
Cheers
Robin
Edit:
Thanks guys. Yep understand now.
As in this case the 0 at the start has a meaning, here the recipient ID in a mailing list, I will use '013' instead of just 013, i.e. a string. I can then split the values in js as each of the 3 values represents a different id which will always be only 1 character long, i.e. 0-9.
A numeric literal that starts with a 0 is treated as an octal number. So 13 from base 8 is 11 in base 10...
Octal numeric literals have been deprecated, but still work if you are not in strict mode.
(You didn't ask, but) A numeric literal that starts with 0x is treated as hexadecimal.
More info at MDN.
In your demo the parameter is called id, which implies you don't need to do numerical operations on it - if so, just put it in quotes and use it as a string.
If you need to be able to pass a leading zero but still have the number treated as base 10 to do numerical operations on it you can enclose it in quotes to pass it as a string and then convert the string to a number in a way that forces base 10, e.g.:
something('013');
function something(id){
alert(+id); // use unary plus operator to convert
// OR
alert(parseInt(id,10)); // use parseInt() to convert
}
Demo: http://jsfiddle.net/XYa6U/5/
013 is octal, not decimal, it's equal 11 in decimal
You should note that 013 starts with a 0. In Javascript, this causes the number to be considered octal. In general you'll want to use the decimal, and hexadecimal number systems. Occasionally though, octal numbers are useful, as this question shows.
I hope this helps! :)
If the first digit of a number is a zero, parseInt interprets the number as an octal.
You can specify a base of ten like this:
parseInt(numberString, 10)
You could also remove such zeros with a regex like this (the result will be a string):
numberString.replace(/^0+/g, '');

Categories

Resources