Ask coding questions

← Back to all posts
How do I convert a alert box to a number in JS
FranklinStopar (20)

So, I am trying to make a program that takes user input from an alert prompt and then uses another on to ask what operation it will use(*,/,-,+) then gets another number...but when i do it, for example, it adds the numbers as strings, so 2+2 is 22, and not 4...

Answered by Coder100 (16792) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16792)

Yeah, because it returns a string. You need to convert it into a number:

let a = Number(prompt("num 1"));
let b = Number(prompt("num 2"));

alert(a + b);
19wintersp (1121)

Just wanted to highlight something about Number: Number parses a string as though it were a JavaScript literal. For example "10" would give 10 (decimal), "0x10" would give 16 (hexadecimal), "0b10" would give 2 (binary), and "0o10" would give 8 (octal). In some cases, this is what you want, but if you would rather it be only for decimal values, use parseInt or parseFloat with base/radix 10.

FranklinStopar (20)

@19wintersp
so i am used to programming in C#, and for that i had to use convert.ToInt32(); is that like the JS version of that then?

19wintersp (1121)

@FranklinStopar Yes, pretty much. parseInt is like int.Parse, and parseFloat is like float.Parse.

FranklinStopar (20)

ok that makes so much more sense thank you @19wintersp

Coder100 (16792)

just remember that js is implicit, and if it is not a valid number it will return NaN instead of an error @FranklinStopar

FranklinStopar (20)

@19wintersp also, I think your connect 4 bot is really cool, i play it in class when im bored...

Coder100 (16792)

hhmmm who wouldn't want that imo @19wintersp

19wintersp (1121)

@Coder100 It's very useful functionality, especially on user input, but that behaviour can be occasionally forgotten.

Coder100 (16792)

yeah that's why i specifically chose Number, it matches the most input types @19wintersp

19wintersp (1121)

@FranklinStopar

Number parses a string as though it were a JavaScript literal

Coder100 (16792)

who wouldn't want their program to match something like 0XDEADBEEF @FranklinStopar

FranklinStopar (20)

@Coder100
I most defintly would want it to match that....how do you do that highlight thing with the text in your comment?

Coder100 (16792)

oops wrong, you have to do the backtick: `
like:

<this see>

@FranklinStopar