Getting Percentage in jQuery

I am trying to get a percentage change in jquery. I have a ticker that pulls 2 values, one of which is a value, and one value is changed. I would like to get a percentage of this and display this value.

I am struggling to do this, and I was wondering if there is an easier way to do this.

The current example can be found here: https://jsfiddle.net/hykdeyoz/

$(document).ready(function () { for (var i = 0; i < gstock.length; i++) { $.getJSON("https://finance.google.com/finance/info?client=ig&q=" + gstock[i] + "&callback=?", function (response) { var stockInfo1 = response[0]; var divContainer = $('*[data-symbol="' + stockInfo1.t + '"]'); var stockString1 = '<div class="stockWrapper">' + divContainer.data('title') + ':'; var stockName1 = stockInfo1.t; var stockChange = ""; 

The value that I would like to change as a percentage will be red and green (green indicates the level of raised or lowered)

Question:

"you want if" 200 "is in red and" 10 "is in green, then it will be displayed as" 200 "in red and" 5% "in green - Sac 8 minutes ago"

yes, although 200 ideally can be hidden. and only percentage is shown. another perk would be, if the percentage was positive, it should be green, and if it is a negative percentage, then it should be red. I used your question to edit the main post. Thanks - Sam Wilson 1 min. Back Edit

Thanks.

+4
source share
3 answers

I have updated my violin to suit your needs. Check this.

 var percentStock = ((parseFloat(stockInfo1.c)/parseFloat(stockInfo1.l)) * 100); percentStock = Number((percentStock).toFixed(2)); 
+4
source

Here is your answer updated script

 var percentage = (parseFloat(stockInfo1.c) * 100 / parseFloat(stockInfo1.l)).toFixed(2); 

I added logic to display green and red here:

 if(parseFloat(stockInfo1.c) > 0) stockChange += '<span class="stockChange "> '; else stockChange += '<span class="stockPrice "> '; 

To ignore NaN:

 var percentage = (parseFloat(stockInfo1.c) * 100 / parseFloat(stockInfo1.l)).toFixed(2); if(isNaN(percentage)) percentage = 0; 

And finally, add a percentage.

 stockChange += percentage + '% </span>'; 

Therefore, you will not get this "background color change" problem.

+1
source

I assume that you want to show percentage changes compared to the previous value, so you need to calculate the old value by changing the change and showing the percentage compared to this.

 var newValue = parseFloat(stockInfo1.l.replace(/,/g, "")); var change = parseFloat(stockInfo1.c.replace(/,/g, "")); var oldValue = newValue - change; var percentChange = (change / oldValue * 100).toFixed(2); stockString1 += '<span class="stockSymbol "> ' + stockInfo1.t + ' </span>'; stockChange += '<span class="stockPrice "> ' + stockInfo1.l + '</span>'; stockChange += '<span class="stockChange "> ' + percentChange + '%</span>'; 

As @blgt noted, there is no data validation, and when a positive or negative value changes, a different color occurs.

+1
source

All Articles