检查Javascript / jQuery中的数字是否为整数

时间:2014-02-25 10:03:06

标签: javascript jquery

我有一些JS:

var updateAmount = function (amount, rate) {
    if (rate > 0 && amount.length > 0 && !isNaN(amount) && amount > 0) {
        amount = Math.round(rate * amount * 100) / 100; // multiply rate with amount and then round to 2 decimals
        $('.you-get').show();
        $('#you-get').text(amount + ' ' + $currencyTo.find(':selected').text());
    } else {
        $('.you-get').hide();
    }
};

我需要的是一个子句,用于检查amount + $currencyTo.find生成的值是否为整数,如果则将.00 添加到其末尾。< / p>

4 个答案:

答案 0 :(得分:4)

if(amount === parseInt(amount)) //returns `true` if it's a integer


var updateAmount = function (amount, rate) {
    if (rate > 0 && amount.length > 0 && !isNaN(amount) && amount > 0 && amount === parseInt(amount)) { //Edited this line
        if(amount === parseInt(amount)) amount += '.00'; //Added this line
        amount = Math.round(rate * amount * 100) / 100; // multiply rate with amount and then round to 2 decimals
        $('.you-get').show();
        $('#you-get').text(amount + ' ' + $currencyTo.find(':selected').text());
    } else {
        $('.you-get').hide();
    }
};

答案 1 :(得分:1)

.toFixed() 方法。

amount = Math.round(rate * amount * 100) / 100;
amount = amount.toFixed(2);

答案 2 :(得分:0)

试试这个:

var updateAmount = function (amount, rate) {
  if (rate > 0 && amount.length > 0 && !isNaN(amount) && amount > 0) {
    amount = Math.round(rate * amount * 100) / 100; // multiply rate with amount and then round to 2 decimals
    $('.you-get').show();
    var val = amount + '' + $currencyTo.find(':selected').text();
    if (val === parseInt(val)){// check if val is an Int
      $('#you-get').text(val.toFixed(2));//add .00 if amount + $currencyTo.find is an Int
    }else{  
      $('#you-get').text(val);
    }
  }else{
    $('.you-get').hide();
  }
};

答案 3 :(得分:0)

您可以使用余数来检查数字是否为整数?例如。

var val = parseFloat(amount) + parseFloat($currencyTo.find(':selected').text());
if ( val % 1 == 0 ) { /* whole number */ } else {/* not whole number */ }

您还可以检查!isNaN(val)

这基本上是从类似问题中提出的答案,请参阅here