以数字格式获取字符串价格

Getting the string price in numeric format

我正在使用 opencart 3.x 并试图将价格转化为数字,以便我可以用它进行计算。我不断收到 NaN 或脚本错误:

<h2><span id="getPrice">{{ price }}</span> /Carton</h2>    

这里我将 id 设置为 getPrice,这样我就可以在页面加载后获取价格,结果是 169.99 美元。这个数字不能用作数字。这就是我遇到的问题。我知道 { { price } } 是 PHp 我相信,但我认为由于数字在我的脚本之前加载,所以我不必担心它?页面加载后,它显示每箱 116.99 美元,我跨出了 {{price}} 这样我就可以把它变成一个数字。

这是我的 javascript。我尝试了不起作用的 parsefloat,以及 alawys 得到“toFixed 不是函数”错误的 toFixed(2)

const getPrice = document.querySelector("[id^='getPrice']").innerHTML;
const getSquareFeetPerBox = document.querySelector("[id^='input-option']").value;
const costPerSqft = getPrice / getSquareFeetPerBox;
const fixxed = parseFloat(getPrice);
document.getElementById("pricePerSqft").innerHTML = ` ( ${costPerSqft}  /per sqft )`;
console.log(fixxed);    

请帮忙,我已经处理这个问题好几个小时了,只需要对价格做一个简单的计算。我使用 console.log 只是为了查看是否记录了一个数字,但它总是 $116.99 或脚本错误...永远不会只是 116.99

提前谢谢你

假设以下 HTML:

<h2><span id="getPrice">9.99</span> /Carton</h2>  
<input type="text" id='input-option' value="10"></input>
<p id="pricePerSqft"> </p>

与以下 JS:

const getPrice = document.querySelector("[id^='getPrice']").innerHTML;
const getSquareFeetPerBox = document.querySelector("[id^='input-option']").value;
const fixed = parseFloat(getPrice.slice(1, getPrice.length));
const costPerSqft = fixed / getSquareFeetPerBox;
console.log(costPerSqft)
document.getElementById("pricePerSqft").innerHTML = ` ( ${costPerSqft}  / per sqft );

您应该能够解析该号码。我使用 String#slice 来获取号码,但根据您对原始 post 的评论,肯定有其他方法可以获取号码。使用像 Mark 建议的正则表达式听起来是一个不错的选择:)

CodePen link 如果你需要,请点击此处:https://codepen.io/travishaby/pen/jRbqMr