Skip to content

Commit

Permalink
Convert jQuery data attribute to number
Browse files Browse the repository at this point in the history
JQuery numeric string data attributes are not casted to numbers
consistently. There are instances when they are kept as string,
this behavior seems to be related to the presence of insignificant
zeros in the original string:

  $('<div data-price="12.00"></div>').data('price')
  > "12.00"

  $('<div data-price="12.10"></div>').data('price')
  > "12.10"

but:

  $('<div data-price="12.1"></div>').data('price')
  > 12.1

So, we need to enforce the typecast to number when summing those
attributes in the function `totalSelectedReturnItemAmount`.

After the sum, the number needs to be converted to a properly
localized amount. For this we leverage the existing function
`formatNumber` from the library `accounting.js`, see

https://github.com/solidusio/solidus/blob/master/backend/vendor/assets/javascripts/solidus_admin/accounting.js
  • Loading branch information
spaghetticode committed Jan 19, 2021
1 parent ed88ebc commit a486ed6
Showing 1 changed file with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,25 @@ Spree.Views.Tables.SelectableTable.SumReturnItemAmount = Backbone.View.extend({
},

totalSelectedReturnItemAmount: function () {
var totalAmount = 0.00;
var totalAmount = 0;
var selectedItems = [];
var decimals = 0;
var separator = Spree.t('currency_separator');
var amount, decimalAmount;

if(this.model.get('allSelected')) {
selectedItems = $('.selectable');
} else {
selectedItems = $(this.model.attributes.selectedItems);
}
selectedItems.each(function(_, selectedItem){
totalAmount += $(selectedItem).data('price');
amount = $(selectedItem).data('price');
decimalAmount = amount.toString().split(separator)[1] || '';
decimals = Math.max(decimals, decimalAmount.length);

totalAmount += parseFloat(amount);
})

return totalAmount;
return accounting.formatNumber(totalAmount, decimals, Spree.t('currency_delimiter'), separator);
},
});

0 comments on commit a486ed6

Please sign in to comment.