0

I'm making some code that scans an item for its price, and the price is located inside a class "cash". The text inside the cash class looks like this

                                        1,000

I need to find a way to convert it to just an integer, rather than a string with lots of empty white space I tried doing this

var cash = document.getElementsByClassName('cash')[0].innerHTML
var parser = parseInt(cash)
console.log(parser)

It just returns "1"

I need to also make it so that it gets rid of the comma, so if the price is 1,000, it will return 1000, and I need to be able to use it as an integer.

duffymo
  • 305,152
  • 44
  • 369
  • 561
J Doe
  • 39
  • 5

2 Answers2

0

Try:

var cash = "1,000";
var parser = parseInt(cash.replace(/,/g, ""));
document.write(parser);

(Note the added semicolons to the end of each line)

This uses cash.replace(/,/g, "") to replace any occurance of a comma in cash, with 'nothing'; i.e. removes any commas

joe_young
  • 4,107
  • 2
  • 27
  • 38
  • Note: This won't behave as expected for millions, etc. – `"1,000,000".replace(",", "") === "1000,000"`. Given a string, `.replace()` will only replace the first occurrence. [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – Jonathan Lonowski Nov 29 '15 at 17:16
  • Great! You can mark it as the correct answer by clicking the green tick to the left of the answer @JDoe – joe_young Nov 29 '15 at 18:46
0

Just remove everything, that doesn't match numbers wuth regex: DEMO

var cash = document.getElementsByClassName('cash')[0].innerHTML
var parser = parseFloat(cash.replace(/[^0-9|^.]/g, ''))
alert(parser)
<div class="cash">1,000.23</div>
neoselcev
  • 138
  • 12