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

问题描述 投票:0回答:1

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

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

在这里我将id设置为getPrice,因此我可以在页面加载后获得价格,它的价格为169.99美元。这个号码不能用作数字。这是我遇到的问题。我知道{{price}}是我认为的PHp,但我认为自从我的脚本加载数字之后,我不必担心它吗?一旦页面加载,它说$ 116.99 /每箱,我跨越{{price}}所以我可以把它变成一个数字。

这是我的javascript。我试过parsefloat哪个不起作用,在toFixed(2)中总是得到“toFixed不是函数”错误

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

我提前谢谢你

javascript opencart-3
1个回答
1
投票

假设以下HTML:

<h2><span id="getPrice">$169.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来获取数字,但根据原始帖子的评论,肯定有其他方法来获取数字。使用像Mark这样的正则表达式听起来像一个可靠的选项:)

如果您需要CodePen链接:https://codepen.io/travishaby/pen/jRbqMr

© www.soinside.com 2019 - 2024. All rights reserved.