Question

Multiplication of two numbers

$(document).ready(function () {
    $("#input1, #input2").change(function () {
        var num = parseFloat($("#input1").val()) * parseFloat($("#input2").val());

        if (num % 1 != 0) {
            num = Math.floor(num * 100) / 100;
        } else {
            num = parseInt(num);
        }

        $("#input3").val(num);
    });
});
  • If the result is integer as 10, it is written as 10. It is ok for me.

  • If the result is as 10.01, it is written as 10.01. It is ok for me.

  • But if the result is as 10.10, it is written as 10.1 instead of 10.10.

    How do display "always" two digits only if there is any decimals?

Was it helpful?

Solution

Try this:

http://jsfiddle.net/qjmve/

$(document).ready(function () {
    $("#input1, #input2").change(function () {
        var num = parseFloat($("#input1").val()) * parseFloat($("#input2").val());

        if (num != parseInt(num))
            num = num.toFixed(2);

        $("#input3").val(num);
    });
});

OTHER TIPS

Use the toFixed() function on numbers with decimals.

if(num.toString().indexOf('.') != -1)
    num = num.toFixed(2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top