# Problem with sum

## Recommended Posts

Hi,

I'm trying to create a little program to calculate the income with a tax, but i've got a problem. Instead of sum the 2 numbers, it aggregate them

Here the example:

Price = 100

Rate = 0.05

Tax = Price * Rate -> 100 * 0.05 = 5

Income = Price + Tax = 100 + 5 = 105 (but the result I obtain is 1005)

I want to specify that the Price is get from a input.

Here the code

```<!DOCTYPE html>
<html>
<body>

<h1>Test</h1>

<input id="price" type="number" onchange="income()">

<p id="result"></p>

<script>
function income(){
let price = document.getElementById("price").value;
let rate = 0.05;

let tax = price * rate;

let income = price + tax;

document.getElementById("result").innerHTML ="The income is: " + income;
}
</script>

</body>
</html>```

How can i fix it?

##### Share on other sites

The JavaScript compiler thinks your concatenating a string with a number, not performing addition. Input always returns a string, regardless of the type attribute. You'll need to typecast the price variable to a number by using any of the following.

• parseInt(price) - If you know its going to be a whole number (which I don't think that's guaranteed). Errors on text.
• parseFloat(price) - If you know it can be a non-whole number. Errors on text.
• Number(price) - This assigns integer or float based on the input. NaN on text.

As an aside

The onchange event fires when the input loses focus while it has a different value.

In addition to onchange, you could add onkeyup to get an output as you type.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.