0

I have to convert the Italian number system to English number system by JavaScript and I have write below code the achieve this.

function fnNumSysConvertor(number) {
    if(number.toString().lastIndexOf(",") == -1 && number.toString().indexOf(".") == 0 )
         return number;
    else if(number.toString().lastIndexOf(",") != -1 && number.toString().indexOf(".") != -1 ) {
         if(number.toString().length === number.toString().lastIndexOf(",") + 1)
             return removeLastComma(number);
         else 
            return replaceDot(number);
     }      
     else if (number.toString().lastIndexOf(",") != -1)
         return removeLastComma(number);
     else if (number.toString().indexOf(".") != -1)
        return replaceDot(number);
     else
        return number;
}

function removeLastComma(number) {
    number=number.substring(0,number.lastIndexOf(","))
    return number.toString();
}

function replaceDot(number) {
    number = number.replace(/\./g, "");     
    return number.toString();
}

Test cases :

fnNumSysConvertor("80"); - 80 - Passed
fnNumSysConvertor("1.220"); - 1220 - Passed
fnNumSysConvertor("227.094,"); - 227.094 - Passed
fnNumSysConvertor("1.083.003,"); - 1.083.003 - Failed. It should be 1083.003

This code is working fine for some cases and for the failed case also I can put a one more if condition and change it, however I feel whatever I am doing is not a generic and best approach.

Could anyone please help to give some idea how can I write some generic code which will be pass in every test cases.

Thanks in advance.

SK.
  • 4,174
  • 4
  • 30
  • 48
  • 1
    Really, they write `1.083.003` as `1083.003` in England, didn't know that ? – adeneo May 13 '14 at 19:48
  • @adeneo number is `1.083.003,` not `1.083.003`. I am not sure but there should be a difference in both. – SK. May 13 '14 at 19:58
  • I cannot see the forest for the trees. I am not familiar in Italian notation and I am too lazy to read about it. Can you describe the Italian notation? – Lajos Arpad May 13 '14 at 20:04
  • @LajosArpad lol i don't know either. if I know that I would have done it already :( – SK. May 13 '14 at 20:10
  • Honestly, never seen the notation 1.083.83, we either write 1083.83 or the high dot, (to separate thousands, for hand written numbers though) OR 1083,83 – Antonio E. May 13 '14 at 20:21
  • Forgot with the last notation (comma for decimals) you can use dot to separate thousands – Antonio E. May 13 '14 at 20:26

0 Answers0