如何在javascript中检查变量类型

时间:2015-01-05 05:43:53

标签: javascript variables

我需要检查变量是整数还是小数。 如果整数只需要显示整数,如果不显示小数点2。 我刚刚使用了

toFixed(2)

但它会显示带有两个小数点的整数

<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>

2 个答案:

答案 0 :(得分:0)

一种简单的方法是使用parseInt函数来获取整数值并检查它是否与原始值相同。如果是,则value为整数,否则为小数。

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

&#13;
&#13;
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);
    }
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

isInteger = function(input) {
  if (typeof input === "number")
    return input % 1 === 0;
}

这将返回输入是否为int。

测试:

isInteger(1);      // true
isInteger(1.01);   // false
isInteger("2");    // false
isInteger("2.02"); // false