Display decimal places in two digits, if only an 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 an integer of 10, it is written as 10. This is normal for me.
  • If the result is 10.01, it is written as 10.01. This is normal for me.
  • But if the result is 10.10, it is written as 10.1 instead of 10.10.

    How to display โ€œalwaysโ€ two digits only if there are any decimal places?

+6
source share
2 answers

Try the following:

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); }); }); 
+11
source

Use the toFixed () function for decimal numbers.

 if(num.toString().indexOf('.') != -1) num = num.toFixed(2); 
+3
source

Source: https://habr.com/ru/post/954820/


All Articles