Jump to content

Problem with sum


LightKira

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?

Link to comment
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.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...