Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Multi product example decimals

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #247421
    jack21
    Participant

    Hello,

    I am looking at the multi product order quantity example provided on this website. I am struggling to get the javascript to show the total prices in two decimal places.

    https://css-tricks.com/multi-product-quantity-based-order-form/

    Any advice?

    #247514
    Mottie
    Member

    In javascript, you can use the toFixed function to do the formatting you desire.

    • Please make sure you pay attention to how it rounds the value.
    • This function converts a number type value into a string, so before performing any calculations, make sure to parse the string back into a number value.
    var tax = .075,
      cost = 10.345,
      total = cost.toFixed(2);
    
    // total = 10.35
    $('#sub-total-container').text('$ ' + total);
    
    // use rounded total to calculate tax
    cost = parseFloat(total);
    total = cost + ( cost * tax);
    total = total.toFixed(2);
    
    // total = 11.13
    $('#total-container').text('$ ' + total);
    
Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.