Mohammad hayajneh
Mohammad hayajneh

Reputation: 674

js function ignores Decimal Numbers

So i made a function that calculate the price by multiplication how many meters i put the problem is when ever i put decimal numbers it ignores it

heres my script

<script>
function getFillingPrice() {
    cake_prices = document.getElementById('price').value;
    filling_prices = document.getElementById('test2').value;
    var t=parseInt(filling_prices);
    var x=parseInt(cake_prices);
    return t*x;
}


function calculateTotal() {
    var total = getFillingPrice();
    var totalEl = document.getElementById('totalPrice');

    document.getElementById('test3').value =total + " دينار ";
    totalEl.style.display = 'block';
}
  </script>

Upvotes: 0

Views: 59

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386540

Beside the parsing problem, you could use


cake_price = +document.getElementById('price').value || 0
//           ^ unary plus for converting to numbner
//                                                   ^^^ default value for falsy values

Together

function getFillingPrice() {
    var cake_price = +document.getElementById('price').value || 0,
        filling_price = +document.getElementById('test2').value || 0;

    return cake_price * filling_price;
}

Upvotes: 1

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

You're converting the values to integers when you get them from the DOM.

Change this...

var t=parseInt(filling_prices);
var x=parseInt(cake_prices);

to this...

var t=parseFloat(filling_prices);
var x=parseFloat(cake_prices);

Upvotes: 1

Related Questions