1

So I have some HTML code:

<input type="number" id="height">

I want to take whatever is entered in this box and use it as an int/float etc. Lets say I enter "2". Heres the JavaScript code:

var test;
var a;
test = document.getElementById('height').value;
a = 2 + test;

When I print a, I get 22. This makes sense, but I want 4. In other words, I want test to be treated as an int/float (whatever is entered in the text box). Is there an HTML input type that will do this for me, or do I have to change it another way (like JavaScript commands).

0

2 Answers 2

2

Use the plus sign (+) a.k.a the unary plus operator as the first token for the variable assignment (rvalue), test = +document.getElementById('height').value

From developer.mozilla.org:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

Working Example

var test = +document.getElementById("height").value;
var a;

a = 2 + test;
alert(a);
<input type="number" id="height" value="5">

Sign up to request clarification or add additional context in comments.

Comments

1

This is because test is a string, not a number. Use Number() to convert it to a number:

a = 2 + Number(test);

For your information, JavaScript is not Java - JavaScript is more for browsers, while Java is generally applied to more general situations - the syntax for each is vaguely similar, but still different. You are using JavaScript.

Comments

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.