Meules
Meules

Reputation: 1389

Jquery calculating problems

I'm trying to create a script that get some values from several selectboxes and then do some math with them. The problem is that the script need to be placed in a SaaS enviroment so my options of doing stuff are every limited. The way described below is the only way to do this.

The problem I'm facing is that I can receive the correct values from the selectboxes but I can't convert them to 2 decimals. Further I can't get the initial value adviesprijs converted to just eg. 1500 instead of 1.5 or 1.500.00. I really can't see what I'm doing wrong.

I've created a fiddle here I think that describes my problem best!

My script

function update_amounts() {

   var perc = '10' || 0; //this is a value from a Twig tag. Not relevant for question!
   var korting = ((100-perc)/100);

    var adviesprijs = '€1.500,00'.replace(/[^\d.]/g, ''); //gives 1.5 or 1.500.00 etc..
    var adviesprijsValue = parseFloat(adviesprijs) || 0;


     var sum = 0.0;
       $('#product_configure_form .product-configure-custom-option select').each(function () {
      var optionText = $(this).find('option:selected').text();
      var matches = optionText.match(/\(([^)]+)\)/g) || [];
        if (matches.length > 0) {
         var priceText = matches[matches.length - 1];
          if (priceText.indexOf("€") > -1) {
          var priceClean = priceText.replace(/[^0-9\+\-\.\,]/g, '');
          var priceValue = parseFloat(priceClean) || 0;

            sum += priceValue;
          }
         }
        });
                  var sum2 = sum+adviesprijsValue;

                  var sumBtw = (sum2*1.21).toFixed(2);
                  $('#amount').text('€' +sum2);//
                  $('#amountBtw').html('(€'+sumBtw+' - Incl. 21% BTW)');//.toFixed(2)
                }

                $(document).ready(function(){
                  $( "#product_configure_form").on("change", ".product-configure-custom-option select", update_amounts);
                });

The HTML is pretty long so best is to take a look at the Fiddle. Can anybody help me to make a correct calculation...?!

Thx in advance

Upvotes: 1

Views: 48

Answers (1)

Random Hunter
Random Hunter

Reputation: 116

Your conversion from Dutch formatting to normal float formatting is incorrect.

Consider using:

.replace(/[^\d,]/g,"").replace(",",".")

Working example: http://jsfiddle.net/pgaphma3/3/

EDIT

To allow also a plus or minus sign use /[^\d,\-+]/g

Upvotes: 1

Related Questions