jHannel
jHannel

Reputation: 203

jQuery Conditional Decimal Greater Than Comparison

I have an odd issue that I'm not sure quite how to fix, but here it goes.

I've got a return from an AJAX query and this is how two parts are returned (and how they look in the preview panel):

id:1
paid: "158.40"
balance: "79.20"

So initially I had just tried the following (after noticing an issue):

if(item.balance > item.paid){
   var test = "balance greater than paid";
}else{
   var test = "balance is not";
}

But in the above case, it returns the first test meaning that somewhere, the it thinks that 79.20 is greater than 158.40, which is obviously not what I want.

So I tried this:

var paid = parseFloat(item.paid).toFixed(2);
var balance = parseFloat(item.balance).toFixed(2);

And just switch the first line of the above conditional statement to if(balance > paid) and it still did the same thing...

So I am at a loss, if anyone can help - I'd be very appreciative.

Upvotes: 3

Views: 1604

Answers (4)

Ruzihm
Ruzihm

Reputation: 20259

Don't use toFixed when comparing those values, because it just gives you another string, which it can't compare numerically in the way you're trying to compare. Just compare the outputs of parseFloat.

var paid = "158.40";
var balance = "79.20";

$(".string").text(paid > balance);

paid = parseFloat("158.40");
balance = parseFloat("79.20");

$(".float").text(paid > balance);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

  String compare:
  <span class="string">

</span>
</div>

<div>
  Float compare:
  <span class="float">

</span>
</div>

Upvotes: 3

samabcde
samabcde

Reputation: 8114

Referring to toFixed method, it is returning a String, not a Number. Hence the comparison result is not expected. There is no need to call this method for your case. If you have concern on the precision, take a look on this question

var item = {
  id: 1,
  paid: "158.40",
  balance: "79.20"
};
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
console.log("paid=" + paid);
console.log("balance=" + balance);
console.log("paid>balance=" + (paid > balance));

Upvotes: 0

Anku Singh
Anku Singh

Reputation: 954

Use it like below

var paid = parseFloat(item.paid);

var balance = parseFloat(item.balance);

Then compare it will take you into right condition

Above you are using toFixed which again returns string.

Upvotes: 0

Mina Ragaie
Mina Ragaie

Reputation: 475

try to use Number() to convert string to numbers first

if(Number(item.balance) > Number(item.paid)){
   var test = "balance greater than paid";
}else{
   var test = "balance is not";
}

Upvotes: 0

Related Questions