Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Culture sensitive ParseFloat Function in JavaScript?

Do anyone have suggestion for writing culture sensitive ParseFloat Function in JavaScript, So that when I have a string 100,000.22 in US culture format the parse float function returns 100000.22 whereas if I enter 100.000,22 in Swedish Culture it returns 100000.22 in float?

like image 678
Faheem Ramzan Avatar asked Feb 09 '11 23:02

Faheem Ramzan


3 Answers

I've improved mwilcox' function to handle values withous separators.

function parseFloatOpts (str) {

     if(typeof str === "number"){
         return str;
     }

     var ar = str.split(/\.|,/);  

     var value = '';
     for (var i in ar) {
         if (i>0 && i==ar.length-1) {
             value += ".";
         }
         value +=ar[i];
     }
     return Number(value);
}
like image 103
Alex Polishchuk Avatar answered Oct 27 '22 16:10

Alex Polishchuk


This is a bit rough-and-ready, but it may be sufficient, allowing you to pass in the thousands and decimal separators:

function parseFloatOpts(num, decimal, thousands) {
    var bits = num.split(decimal, 2),
        ones = bits[0].replace(new RegExp('\\' + thousands, 'g'), '');
        ones = parseFloat(ones, 10),
        decimal = parseFloat('0.' + bits[1], 10);
        return ones + decimal;
}

Examples:

parseFloatOpts("100.000,22", ',', '.'); //100000.22
parseFloatOpts("100,000.22", '.', ','); //100000.22

NB that this doesn't ensure that the thousands separator really does represent thousands, etc., or do lots of other safeguarding that you may wish to do, depending on the importance of the function.

like image 21
lonesomeday Avatar answered Oct 27 '22 16:10

lonesomeday


var parse = function(st){
   if(st.indexOf(",") === st.length-3){
      st = st.replace(".", "").replace(",", ".");
   }else{
       st = st.replace(",", "");
   }
   return parseFloat(st, 10)
}

console.log(parse("100,000.22")) // 100000.22
console.log(parse("100.000,22")) // 100000.22

I'm just checking if there is a comma in the 3rd-to-last position. This could be further refined to check if there is a period in the 4th to last position in the case thee is no comma (such as 100.000)

like image 39
mwilcox Avatar answered Oct 27 '22 16:10

mwilcox