简体   繁体   中英

jQuery/Javascript splitting string calculation

I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity . These values are obviously multiplied together.

I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).

My code:

jQuery("#quantity").change(function() {

         jQuery("#pricediv").hide();

// store form values
         var origprice = jQuery(".orig_price").val().substr(1); 
         var qty = jQuery("#quantity").val();

// calculate price
         var sumValue = origprice * qty;

// split price
         var splitprice = sumValue.split("."); 
         var pricepound = splitprice[0];
         var pricepenny = splitprice[1].substring(0,2);   

// update price

         jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
         jQuery("#pricediv").fadeIn(1500);
});

If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?

You'll want to use sumValue.toFixed(2)

var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70

.split does not exist on numeric types. You would have to use sumValue.toString().split('.') , and either way, this would be more inconvenient than simply sticking to .toFixed

You can use toFixed and parseInt() like so:

jQuery("#quantity").change(function() {

         jQuery("#pricediv").hide();

// store form values
         var origprice = parseInt(jQuery(".orig_price").val().substr(1),10); 
         var qty = parseInt(jQuery("#quantity").val(),10);

// calculate price
         var sumValue = origprice * qty;

// split price
         var price = sumValue.toFixed(2);  

// update price

         jQuery("#pricediv").html('£' + price);
         jQuery("#pricediv").fadeIn(1500);
});

toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM