4

I'm trying to get the text element from a div that has this content: <div class="balance"...>$500.48</div>

What I need is to get the 500.48 as a value, not a as string.

I have used alert($(".balance").text()) to check if it is returning the content and it does, but I need it to be a number. I know that if I store the string on a variable and do this:

x =  $(".balance").text() ;
x = +x;

It'll convert the string into a number, so I tried to ignore the $ but I had no success. What would be the best way to do it?

JosEvora
  • 134
  • 1
  • 9

2 Answers2

3

Try

var val = parseFloat($(".balance").text().replace('$',''));


.parseFloat()
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

Handles Any Currency Symbol

The following uses a regular expression so your code will work with any currency.

var balanceValueElementValue1 = parseFloat($('.balance').text().replace(/[^0-9\.]/g,''));

Quick Markup Suggestion

You might want to house your value inside a span element and add an identifier to the value element so you can target it more consistently and accurately.

<div class="balance">
    <span id="balance-value-1">$500.48</span>
</div>

JQuery

var balanceValueElementValue1 = parseFloat($('#balance-value-1').text().replace(/[^0-9\.]/g,''));

JavaScript

var balanceValueElement = document.getElementById("balance-value-1");
var balanceValueElementInnerText = balanceValueElement.innerText;
var balanceValueElementValue1 = parseFloat(balanceValueElementInnerText.replace(/[^0-9\.]/g,''));
Siriquelle
  • 201
  • 2
  • 5