Reputation: 13853
Here is my Javascript:
var total = $(this).text();
var calc = total * 100;
var paid = calc * 0.333;
The HTML is simple:
<div class="price"><span>£0.21</span></div>
How can I remove the '£' char from the string so I can do the maths?
Upvotes: 2
Views: 206
Reputation: 51817
Upvotes: 1
Reputation: 1760
parseint is wrong.. it would be parsefloat...
but you need to strip the first char before you parsefloat otherwise it will return NaN (not a number)
var total = "£0.21";
total = total.substring(1);
total = parseFloat(total);
var calc = total * 100;
var paid = calc * 0.333;
alert(paid);
Upvotes: 0
Reputation: 116180
Use SubStr to copy from the second character (#1). Use parseFloat to convert to float.
var total = $(this).text().substr(1).parseFloat();
var calc = total * 100;
var paid = calc * 0.333;
Upvotes: 0
Reputation: 660
If you always have a '£' sign at the beginning of your string, you can use a substring before assigning total (which will cast from string to number, correctly this time).
You can also rely on a regular expression such as
/[-+]?[0-9]*\.?[0-9]*/
Cheers,
-stan
Upvotes: 1
Reputation: 70879
You need to slice
the string to remove the '£':
var total = $(this).text().slice(1);
Upvotes: 1
Reputation: 322592
This will remove all characters from the string that are not a number or decimal point.
var total = $(this).text().replace(/[^\d.]/g,'');
var calc = total * 100;
var paid = calc * 0.333;
Useful if there are any comma separators as well.
The *
will take care of the conversion from String. If you want something more explicit, you can use the unary +
operator.
var total = +($(this).text().replace(/[^\d.]/g,'')); // <-- has + at beginning
var calc = total * 100;
var paid = calc * 0.333;
Upvotes: 4
Reputation: 179256
check out the parseFloat function.
Edit: whoops, i meant to write parseFloat; couple bits of difference.
Upvotes: 0