Designer
Designer

Reputation: 485

Add 2 form fields together using JS

I am creating a script which included a calculation to add 2 form form fields together and out the result onkeyup

<script>
function sum()
{
var w = document.getElementById('amount').value || 0;
var x = document.getElementById('vat').value || 0;
var z=parseInt(w)+parseInt(x);
var twoPlacedFloat = parseFloat(z).toFixed(2) 
document.getElementById('final').value=twoPlacedFloat;
};   
</script>

This is working however it does not add the decimals together, what do I need to change to make it do this?

Example: Unit Cost (12.00) + VAT (2.40) should total 14.40 however it is showing 14.00?

enter image description here

Upvotes: 3

Views: 218

Answers (6)

Taki
Taki

Reputation: 17654

Cast the string to a number using +

var z= +w + +x;

const a = "3";
const b = "4.2";

const result = +a + +b;

console.log(result);

Upvotes: 0

brk
brk

Reputation: 50291

According to mdn

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.

You can replace parseInt with unary operator or use parseFloat on the value

function sum() {
  var w = document.getElementById('amount').value || 0;
  var x = document.getElementById('vat').value || 0;
  var z = +w + +x;
  var twoPlacedFloat = parseFloat(z).toFixed(2)
  document.getElementById('final').value = twoPlacedFloat;
};
<input id="amount">
<input id="vat">
<input id="final">
<button type="button" onclick="sum()">Add</button>

Upvotes: 0

Vinie
Vinie

Reputation: 2993

Change this var z=parseInt(w)+parseInt(x); to var z=parseFloat(w)+parseFloat(x);

<script>
function sum()
{
    var w = document.getElementById('amount').value || 0;
    var x = document.getElementById('vat').value || 0;
    var z=parseFloat(w)+parseFloat(x);
    var twoPlacedFloat = parseFloat(z).toFixed(2) 
    document.getElementById('final').value=twoPlacedFloat;
 };   
</script>

Upvotes: 1

Mickey Dhami
Mickey Dhami

Reputation: 100

You need parseFloat() instead of parseInt().

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18975

You need change from parseInt to parseFloat

var z=parseFloat(w)+parseFloat(x);

var w = 12.2;
var x = 2.4;
var z=parseFloat(w)+parseFloat(x);
var twoPlacedFloat = parseFloat(z).toFixed(2) 
document.getElementById('final').value=twoPlacedFloat;
<input type='text' id='final'/>

Upvotes: 1

Andrew Daly
Andrew Daly

Reputation: 537

change

var z=parseInt(w)+parseInt(x); 

to

var z=parseFloat(w)+parseFloat(x);

parse int will not include decimals

Upvotes: 4

Related Questions