Last Updated: November 21, 2018
·
2.051K
· 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");
  }
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside