Вопрос

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?

Это было полезно?

Решение

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);
    });
});

Другие советы

Use the toFixed() function on numbers with decimals.

if(num.toString().indexOf('.') != -1)
    num = num.toFixed(2);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top