JavaScript Math Percentage
12,851
Solution 1
Using Math.round
will round your result to the nearest whole number. You can used just toFixed
Which will round it correctly to 386.67
Solution 2
Try this:
var price = parseFloat($(".price").html());
Author by
user2203362
Updated on August 21, 2022Comments
-
user2203362 almost 2 years
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:
<div class="price">420.29</div>
I want to remove 8% off
.price
and have it fixed to two decimal places and store it as a variable.Here's the JS I have so far:
var price = $(".price").html(); var priceafter = Math.round(price - price * 8 / 100).toFixed(2);
priceafter
returns back as 387.00 instead of 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:var price = $(".price").html(); var priceafter = (price - price * 8 / 100).toFixed(2);