prompt
is extremely basic and offers no way to constrain the input other than the way browsers do by default (e.g., no line breaks).
Instead, convert the string to number afterward. There are a lot of ways to do that:
- Unary
+
: var jonage = +prompt("enter the johns age");
Number
: var jonage = Number(prompt("enter the johns age"));
parseInt
: var jonage = parseInt(prompt("enter the johns age"));
parseFloat
: var jonage = parseFloat(prompt("enter the johns age"));
Unary +
and Number
:
...work the same way:
- They convert the entire string to number if possible, yielding
NaN
if the entire string can't be converted to number. So +"123abc"
is NaN
.
- They convert an empty string (
""
) to 0
(surprisingly).
- They respect JavaScript syntax for specifying the number base (radix), so
+"0x10"
is 16 and +"0o10"
is 8
.
parseInt
- Converts only as much of the string as it can before the first invalid character, not the whole string. So
parstInt("123abc")
is 123
.
- Converts an empty string (
""
) to NaN
(not 0
).
- Respects JavaScript syntax for specifying the number base (radix), e.g.,
parseInt("0x10")
is 16.
- Also lets you specify the radix explicitly as a second argument, to force it to treat the input as being in that number base:
parseInt("0x10", 10)
is 0
(because the x
becomes invalid, 0x
is no longer treated as indicating the number base. This used to be important with decimal in case end users entered strings like "010"
and browsers implemented "legacy" Octal (leading 0
instead of leading 0o
), but it's been eight years now (since the 5th edition spec) since parseInt
was officially not allowed to do that.
- As the name suggests, only converts the part of the string that defines a whole number (integer).
parseFloat
Like parseInt
, but does fractional numbers and doesn't do radix prefixes. parseFloat("0x16")
is 0
, because the x
is invalid (because it doesn't do radix prefixes).