Update product price on quantity increase/decrease

Hi guys,

I’ve been playing around with some Jquery to update my product price, weight and length of use.

As a start I can update the price on the page when the user changes the quantity value but I can’t find a good cross browser compatible way of rounding up the numbers. I can see that Webflow are doing this already in the cart, how are they doing this exactly? @federico @timdalrymple

Example here:

Current Code:

<script>
// Get the price of product
var price = $(".pdp-hero__form-price").text();

// Convert the price to a number value
var priceNumber = Number(price.replace(/[^0-9.-]+/g,""));

// When Page loads update subtotal
$(function() {
  // Get the quantity
    var quantity = $(".pdp-hero__quantity").val();
    
  // Multiply the quantity by the converted price number value
    var subtotal = (quantity*priceNumber);
    
  // Code to output rounded subtotal to page
      $( ".pdp-hero__form-price" ).text( "£" + subtotal );
});

// When user increases or decreases the Quantity Field 
$(".pdp-hero__quantity").bind('keyup mouseup', function () {
  
  // Get the quantity
    var quantity = $(".pdp-hero__quantity").val();
    
  // Multiply the quantity by the converted price number value
    var subtotal = (quantity*priceNumber);
    
  // Code to output rounded subtotal to page
      $( ".pdp-hero__form-price" ).text( "£" + subtotal );
});

</script>

Thanks,

Joe

1 Like

Hi @JoeDigital!

You’re running into a tricky Javascript problem: floats precision. If you want a full understanding of the issue here is some extensive blog post around it: What Every JavaScript Developer Should Know About Floating Points | Modern Web - Web3, Business & Technology

Luckily the solution for you is pretty simple! Use this to calculate your subtotal and rounding it to two decimals:

var subtotal = parseFloat(quantity*priceNumber).toFixed(2)

Let me know if you solved your problem!

Best,
Federico

@federico, you make my life easier :joy: thank you!

1 Like

@JoeDigital Hey! Were you able to get this code working? Because it doesn’t seem to work properly for me.