Last Updated: November 21, 2018
·
1.708K
· Eduardo Martines

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");
  }
}