JavaScript 数学百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15599204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Math Percentage
提问by user2203362
I have an element where I need to remove a percentage of it.
我有一个元素需要删除它的一部分。
I've stored the original price as a variable and have another variable to work out the price after the percentage has been taken.
我已将原始价格存储为变量,并在采用百分比后使用另一个变量来计算价格。
Here's the HTML:
这是 HTML:
<div class="price">420.29</div>
I want to remove 8% off .priceand have it fixed to two decimal places and store it as a variable.
我想删除 8% 的折扣.price并将其固定为两位小数并将其存储为变量。
Here's the JS I have so far:
这是我到目前为止的 JS:
var price = $(".price").html();
var priceafter = Math.round(price - price * 8 / 100).toFixed(2);
priceafterreturns back as 387.00 instead of 386.66.
priceafter返回 387.00 而不是 386.66。
Update
更新
Thanks to @datasage for point out I was using Math.round. This is what I've changed it to and it seems to be working:
感谢@datasage 指出我正在使用Math.round. 这就是我将其更改为的内容,并且似乎可以正常工作:
var price = $(".price").html();
var priceafter = (price - price * 8 / 100).toFixed(2);
回答by datasage
Using Math.roundwill round your result to the nearest whole number. You can used just toFixedWhich will round it correctly to 386.67
使用Math.round会将您的结果四舍五入到最接近的整数。您可以只使用toFixedwhich 会将其正确四舍五入为 386.67
回答by Athlan
Try this:
试试这个:
var price = parseFloat($(".price").html());

