Simon Fabb
Simon Fabb

Reputation: 53

Parse and compare currency values

I have two divs named with the classes leased and limit. In each div is a value and I am using jQuery to hide another div, called #next, if the value in the .leased div is higher than the value in the .limit div.

It all works great with the following code, however I plan for the values in the divs to be currencies i.e. £10,000.00. As such, the jQuery isn't returning anything.

What do I need to do to the below code in order for it to parse the currency value, please?

<div class="limit">£10,000.00</div>
<div class="leased">£11,000.00</div>
<div id="next">next</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $("#next").toggle(parseInt($(".leased").text(), 10) < parseInt($(".limit").text(), 10));
</script>

Thank you.

Upvotes: 1

Views: 2700

Answers (2)

Rafael
Rafael

Reputation: 18522

One option is to use a ready-made library that can convert currency strings into numbers, like Numeraljs

Otherwise, as suggested in other answers and comments, either remove all non-numeric characters or create a regular expression that potentially (based on your needs) also supports comma as decimal separator, as such syntax is used in some countries.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use a regular expression to remove the non-numerical characters from the text() then run them through parseFloat() before making the comparison, like this:

var limit = parseFloat($('.limit').text().replace(/[^0-9\.]+/g,""));
var leased = parseFloat($('.leased').text().replace(/[^0-9\.]+/g,""));
$("#next").toggle(leased < limit);

Working example

Alternatively you could add the plain values to the HTML using data-* attributes and perform the logic on those values directly, like this:

<div class="limit" data-val="10000.00">£10,000.00</div>
<div class="leased" data-val="11000.00">£11,000.00</div>
<div id="next">next</div>
$("#next").toggle($('.leased').data('val') < $('.limit').data('val'));

Working example

Upvotes: 3

Related Questions