skip to Main Content

I’m working in Shopify with it’s currency switcher and the problem is, the client I’m working with wants every currency bar the default (GBP) to round it’s price up to the nearest whole number, so $458.54 becomes $459.

I almost got it to work, except when more than one .money element is present, it seems to break and merges them together.

The JS code is:

var all = $(".money")
 .map(function() {
return this.innerHTML;
})
.get();

var all = [all, ","];
var arrayLength = all.length;
for (var i = 0; i < arrayLength; i++) {
  //Do something
}
console.log("array:", all);
var regex = all.toString().replace(/[^0-9.]/g, "");

var regex = [regex, ","];
var regexarrayLength = regex.length;
for (var i = 0; i < regexarrayLength; i++) {
 //Do something
}
console.log("arrayregex:", regex);
console.log("regex:", regex);
var rounded_currency = Math.round(regex);
console.log("rounded_currency:", rounded_currency);
$("#update").click(function() {
   alert(rounded_currency);
});

$(document).ready(function() {
   $(".priceUpdate").text(regex);
   $(".priceRound").text(rounded_currency);
});

CodePen Example

2

Answers


  1. To achieve expected result, use below option

    Changing array of prices to rounded prices array,as regex is not a proper array that is why it is throwing NaN

    Updated codepen with JPY value for testing

     console.log("array:", all);
    
        var prices = all[0].map(function(num){
          return var prices = all[0].map(function(num){
      return Math.round(num.replace(/,/g, '').substr(1));
    })
    console.log(prices)
        })
        console.log(prices);//rounded prices [6454,6454,454,644,6564454]
    

    Codepen-https://codepen.io/nagasai/pen/VbMZBz?editors=1111

    Login or Signup to reply.
  2. You can make use of javascript’s Math.ceil() function to round up to the nearest integer.

    For example, loop over the array of all selectors with the .money class and first strip the dollar sign. Then call Math.ceil().

    var all = $(".money").map(function() {
        return this.innerHTML;
    }).get();
    //["$6453.65", "$6453.65", "$453.65", "$643.65", "$6564453.65"]
    
    var rounded = all.map(function(x) {
      var numbers = x.replace(/[^0-9]/, '');
      return Math.ceil(numbers);
    });
    //[6454, 6454, 454, 644, 6564454]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search