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);
});
2
Answers
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
Codepen-https://codepen.io/nagasai/pen/VbMZBz?editors=1111
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().