Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display decimals two digits unless integer

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?

like image 264
june8 Avatar asked Sep 27 '13 22:09

june8


2 Answers

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);
    });
});
like image 169
Jason P Avatar answered Oct 13 '22 09:10

Jason P


Use the toFixed() function on numbers with decimals.

if(num.toString().indexOf('.') != -1)
    num = num.toFixed(2);
like image 30
Trevor Avatar answered Oct 13 '22 08:10

Trevor