Streaming live at 10am (PST)

Update product price on quantity increase/decrease


#1

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:
https://www.naturalbarber.co/product/hades-matte-paste

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


#2

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: https://modernweb.com/what-every-javascript-developer-should-know-about-floating-points/

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


#3

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