0

i need to check a variable whether it is an integer or a decimal one. if integer just have to showing the integer if is not show the decimal point up 2. i just used the

toFixed(2)

but it will show the integer number also with two decimal points

<script>
function getDisco() {

  gross = "<?php echo $GROSS_NET ?>";
  dis = document.getElementById('Discount').value;

  document.form3.Discount.value = ((dis/100) * 100).toFixed(2) ;

 document.form3.dis_perc.value =  (((dis/gross) * 100)).toFixed(2) ;
 document.form3.net_tot.value = (gross - dis).toFixed(2);
 document.form3.gross.value = ((gross/100) * 100).toFixed(2);

}
</script>
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
NASIK NSK
  • 55
  • 1
  • 11

2 Answers2

0

One simple way could be to use parseInt function to obtain the integer value and check if it is the same as the original. If it is, then value is an integer, otherwise it is a decimal.

function func(value) {
    var integer = parseInt(value);
    if(integer === value) {
        // value is an integer
    } else {
        // value is a decimal
    }
}

function showResult() {
  var num = document.getElementById("num").value;
  if(num) {
      func(num);
  }
}

function func(value) {
    var integer = parseInt(value);
    if(integer == value) {
        document.getElementById("result").value = integer;
    } else {
        document.getElementById("result").value = parseFloat(value).toFixed(2);
    }
}
<input id="num" type="text" placeholder="Enter number here">
<button onclick="showResult();">Show Result</button><br />
<p>Result</p><input id="result" type="text" readonly>
nem035
  • 34,790
  • 6
  • 87
  • 99
0
isInteger = function(input) {
  if (typeof input === "number")
    return input % 1 === 0;
}

This will return whether the input is an int or not.

Test:

isInteger(1);      // true
isInteger(1.01);   // false
isInteger("2");    // false
isInteger("2.02"); // false    
  • @RobG, updated answer. If you're referring to the old answer, it would in the end return `false`, because `NaN % 1 === 0` is false. –  Jan 05 '15 at 05:53
  • Yeah, playing comment tag. ;-) Posted my answer as a comment since it's closed. – RobG Jan 05 '15 at 06:02