JS: Convert price by any string to float
usage
priceUtils.convertToFloatByAnyFormat(priceValueVariable);
code
var priceUtils = {
convertToFloatByAnyFormat: function(price){
var decimal_separator = price.charAt(price.length - 3);
if (decimal_separator == ","){
price = price.replace(".", "");
price = price.replace(",", ".");
}
else if (decimal_separator == "."){
price = price.replace(",", "");
}
else {
price = price.replace(/[\.,]/, "");
}
price = parseFloat(price);
return price || "";
}
}
test
var testPriceConvertion = function(){
var test = ["1000", "1.000,00", "1000,00", "1000.00", "1,000.00", "1,000", "1.000"];
console.log("Testing convertion " + test);
for (var i in test){
console.log(priceUtils.convertToFloatByAnyFormat(test[i]) == "1000.00");
}
}
Written by Eduardo Martines
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Test
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#