Here is my J开发者_开发百科avascript:
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?
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;
You need to slice
the string to remove the '£':
var total = $(this).text().slice(1);
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
- use slice(), substr() or substring() to cut out the part you need
- use parseFloeat() or parseInt() before doing calculations with your number to be sure it is a number
check out the parseFloat function.
Edit: whoops, i meant to write parseFloat; couple bits of difference.
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;
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);
精彩评论