Search code examples
javascriptjquerycurrency

jQuery formating universal currency data


I'm trying to clear multiple currencies (like the US and EU) and round up. What I'm trying to do is;

10.30 → 10
10.60 → 11
849.95 → 850
1,022.20 → 1022
1.022,20 → 1022
230,20 → 230
30,20 → 30

I can do it if it's separated by a dot but the comma ones don't work https://jsfiddle.net/pmhgx7ut/


Solution

  • Building on what you already wrote, you can try the following:

    var price = "1.022,20";
    
    // comma and dot case
    if (price.indexOf(',') < price.indexOf('.')) {
    var price = price.replace(/[^0-9\.\,]/g, '');
    var price = price.replace(",","");
    };
    
    // comma case
    if (price.includes(",")==true && price.includes(".")==false)
    {var price = price.replace(",",".");}
    
    else //dot and comma case
    {
    if (price.indexOf('.') < price.indexOf(',')) {
    var price = price.replace(",",".");
    var price = price.replace(".",",");
    var price = price.replace(/[^0-9\.\,]/g, '');
    var price = price.replace(",","");};
    };
    
    var price = Math.round(price);
    alert(price);