Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }});
like image 471
ondrobaco Avatar asked Nov 19 '25 09:11

ondrobaco


2 Answers

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.

like image 154
James Wiseman Avatar answered Nov 21 '25 23:11

James Wiseman


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);
like image 27
rahul Avatar answered Nov 21 '25 22:11

rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!