1

I've got some 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();
    }
};

What I need is a clause that checks if the value generated from amount + $currencyTo.find is a whole number, if it is then add .00 to the end of it.

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
user3087370
  • 33
  • 2
  • 11
  • amount = Number(amount); rate = Number(rate); will this help ? – Triode Feb 25 '14 at 10:07
  • 1
    Maybe amount.toFixed(2); I'm not sure what you mean by amount + $currencyTo.find as that seams to be a string and not a number since you are appending empty space between + ' ' + – Goran.it Feb 25 '14 at 10:07

4 Answers4

5
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();
    }
};
alexP
  • 3,672
  • 7
  • 27
  • 36
1

There is .toFixed() method.

amount = Math.round(rate * amount * 100) / 100;
amount = amount.toFixed(2);
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Try this :

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();
  }
};
R3tep
  • 12,512
  • 10
  • 48
  • 75
0

Can you use the remainder to check if the number is a whole number? E.g.

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

You could also check that !isNaN(val)

This is essentially the answer suggested from a similar question, see here

Community
  • 1
  • 1
Kiran
  • 1,708
  • 1
  • 11
  • 14