-->

Problem using jQuery calculation with European-for

2019-09-12 11:42发布

问题:

I am calculating rows with a total with the jQuery.Calculation plugin but the total is ignoring everything after the decimal symbol. I suspect the fix lies in the regex but I can't figure out where.

The following method should set the default correct for European decimals, it works pr row but the sum method for the calculation is ignoring the decimal numbers. The regex below is a fix for the official release but it is still not working correct.

$.Calculation.setDefaults({
    reNumbers: /(-|-\$)?(\d+(.\d{3})*(\,\d{1,})?|\.\d{1,})/g
, cleanseNumber: function (v) {
    return v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".");
}
});

Example: 7834,45 * 1 gives the correct sum of 7834,45 for that line, but when calculating the total using jQuery.Calculation sum method this comes out as 7834 with no decimals

Here is the code calculating the totals, more or less ripped straight from the examples

$("[id^=total_umva_item_]").calc(
    // the equation to use for the calculation
            "qty * price",
    // define the variables used in the equation, these can be a jQuery object
            {
            qty: $("input[name^=antall_]"),
            price: $("input[name^=price_]")
        },
    // define the formatting callback, the results of the calculation are passed to this function
            function (s) {
                // return the number as a dollar amount
                return "kr " + s.toFixed(2);
            },
    // define the finish callback, this runs after the calculation has been complete
            function ($this) {
                // sum the total of the $("[id^=total_item]") selector
                var sum = $this.sum(); <- The sum is calculated without decimals
                $("#invoice-totals-net").text(
                    "kr " + sum.toFixed(2)
                );
            }
        );

Using the default regex for US number style this work correctly but I need the calculations to work with , as the decimal symbol

回答1:

I got it working. I contacted the author and he passed me the defaults below. What you need to be aware of too is that the grand total is calculated by summing the row totals so be careful to print out the correct decimal symbol in the row totals as well.

$.Calculation.setDefaults({
  // a regular expression for detecting European-style formatted numbers

  reNumbers: /(-|-\$)?(\d+(\.\d{3})*(\,\d{1,})?|\,\d{1,})?/g
  // define a procedure to convert the string number into an actual usable number
  , cleanseNumber: function (v){
     // cleanse the number one more time to remove extra data (like commas and dollar signs)
     // use this for European numbers: v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".")

     return v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".");
  }
})