JavaScript 数学不起作用

标签 javascript

这是我的 JavaScript:

var total = $(this).text();
var calc = total * 100;
var paid = calc * 0.333;

HTML 很简单:

<div class="price"><span>£0.21</span></div>

如何从字符串中删除“£”字符以便进行数学计算?

最佳答案

这将从字符串中删除所有非数字或小数点的字符。

var total = $(this).text().replace(/[^\d.]/g,'');
var calc = total * 100;
var paid = calc * 0.333;

如果还有逗号分隔符,则很有用。

* 将负责字符串的转换。如果您想要更明确的内容,可以使用一元 + 运算符。

var total = +($(this).text().replace(/[^\d.]/g,'')); // <-- has + at beginning
var calc = total * 100;
var paid = calc * 0.333;

关于JavaScript 数学不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4586213/

相关文章:

javascript - 基本 JQuery Slider - 如何删除底部的幻灯片编号?

javascript - 浏览器更新脚本

javascript - 无法使用 jQuery 获取 html 表中的同级值

javascript - Firefox Web 扩展覆盖新标签页

javascript - Firefox WebExtension - chrome.tabs.query

javascript - 为什么这个 SFTP 下载这么慢?

javascript - JQuery 追加行为

javascript - "Access is denied"访问 iframe 文档对象时出错

javascript - 将字符串与数组匹配

javascript - 在 GWT 中使用 jQuery 工具——有没有办法允许交换?