jQuery Conditional Decimal Greater Than Comparison

2424 views jquery
0

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.

answered question

Are the variables paid, balance already defined /available in the scope?

3 Answers

12

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>

posted this
11

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";
}

posted this
0

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.

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories