ondrobaco
ondrobaco

Reputation: 737

simple calculation of integer and decimal number in jquery

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.

Does anyone know what is the issue?

Thank you.

 $(function(){ // bind the recalc function to the quantity fields

    $("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');

    $("#quantity").bind('keyup', recalc);

    function recalc(){
        var quantity = $('#quantity').val();
        var creditPrice = $('#creditPrice').val();
        var total = quantity * creditPrice;
        $("#total").text(total);
    }});

Upvotes: 2

Views: 10881

Answers (3)

Mutation Person
Mutation Person

Reputation: 30520

Use parseFloat on the values, and alert each one individually to test.

A few other (unrelated) improvements:

  1. Use keyup() function:

    $("#quantity").keyup(recalc);
    
  2. Make function anonymous:

    $("#quantity").keyup(function(){...});
    
  3. Use $(this) on #quantity in the function to avoid calling the jQuery selector again

You could also consider condensing this into a single line of code:

    $("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));

To zero-pad you might try something toFixed():

var num = 10;
var result = num.toFixed(2); // result will equal 10.00

I got this snippet from the following site

http://www.mredkj.com/javascript/numberFormat.html

Hope this helps.

Upvotes: 5

Sarfraz
Sarfraz

Reputation: 382831

If you are interested in whole number only you can use this function instead:

parseInt

Upvotes: 0

rahul
rahul

Reputation: 187100

use

parseFloat

before calculation on both numbers which parses a string argument and returns a floating point number.

var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);

Upvotes: 5

Related Questions