0

I have 2 input box value `"bill_amount" with value 1250, "xray" with value 0

when i tried to find the sum it returns 12500 but when i tried to find the subtracted value it returns 1250 . why for addition it concat 0 while subtraction not including 0.

And how to avoid that?

 console.log( document.getElementById("bill_amount").value-document.getElementById("xray").value); 
User57
  • 2,453
  • 14
  • 36
  • 72

4 Answers4

0

You need to parse your values using parseFloat():

function calculate() {
  console.log(parseFloat(document.getElementById("bill_amount").value) - parseFloat(document.getElementById("xray").value));
}
<input type='text' id='bill_amount' />
<input type='text' id='xray' />
<button onclick="calculate()">Calculate</button>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
0

- converts strings to numbers:

"1250" - "0" => 1250

+ does not:

"1250" + "0" => "12500"

So may convert first:

+"1250" +" 0" => 1250
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You need to parse your values as numbers:

var billAmount = document.getElementById("bill_amount");
var xray = document.getElementById("xray");
var calculate = document.getElementById("calculate");

calculate.onclick = function() {
  console.log(parseFloat(billAmount.value, 10) - parseFloat(xray.value, 10));
}
<input id="bill_amount" type="number" min="0" value="1250" step="0.0001"/>
<input id="xray" type="number" min="0" value="0" step="0.0001"/>
<input id="calculate" type="button" value="calculate" />
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
0
 console.log(eval( document.getElementById("bill_amount").value-document.getElementById("xray").value));

Try this

Anubrij Chandra
  • 1,592
  • 2
  • 14
  • 22