Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 760
jHannel Avatar asked Mar 05 '26 05:03

jHannel


1 Answers

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>
like image 148
Ruzihm Avatar answered Mar 06 '26 18:03

Ruzihm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!