Jerry Svensson Jerry Svensson - 1 year ago 64
jQuery Question

Get percentage between numbers and add results to div

Im trying to calculate the percentage between numbers and ad the results to a div.

The HTML looks something like below - two divs with numbers and a placeholder a element for the results. One of the divs has a number i cant control with currency symbol, a dot and a space in the end - the second number i set manually and can control.

First I tried the script from this thread: (solved) jquery: percentage of two numbers

But I couldn't get that to work.

Second I tried this script:

$('.left').each (function() {
var frstCol = $(this).find('em.price.product-card-price').text();
var seCol = $(this).find('em.price.product-card-price.before').text();

var result = (parseInt(frstCol) / parseInt(seCol))* 100 ;


This outputs a number, 100, which of course is not correct.

How do I do this? It needs to be in an .each functions since I have several elements, and I need the numbers to be rounded of to an even number, like -16%, -50% etc.

<div class="left">
<em class="price product-card-price">€1.019&nbsp;<span class="vatstatus">Exclusief BTW</span></em>
<em class="price product-card-price before">1519</em>
<a class="pricebubble"></a>

Answer Source

The issue with your code is that the text() values from the em elements cannot be directly converted to numbers using parseInt. You need to remove the Euro symbol, the thousand separator and ensure the start of the string is the first digit of the numerical value by using trim(). From there your calculation works:

$('.left').each(function() {
    var frstCol = parseInt($(this).find('em.price.product-card-price').text().trim().replace(/[€\.]/g, ''), 10);
    var seCol = parseInt($(this).find('em.price.product-card-price.before').text().trim(), 10);        
    var result = (frstCol / seCol) * 100;
    $(this).find('a.pricebubble').text(result || 0);

Working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download