user2203362
user2203362

Reputation: 259

JavaScript Math Percentage

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);

Upvotes: 4

Views: 15286

Answers (2)

datasage
datasage

Reputation: 19563

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

Upvotes: 5

Athlan
Athlan

Reputation: 6619

Try this:

var price = parseFloat($(".price").html());

Upvotes: 1

Related Questions