Reputation: 61
I have a stream of strings representing currency values from where I need to extract integers.
These strings may or may not have characters such as "$", "€", "-", space "." and "," that can alternate to separate decimals and digit groups. These are the examples of strings and the value that I need to extract from them example:
"1,423,433.00" = 1423433
"1.355,22€" = 1355
" CAD$764.35" = 764
"$734242" = 734242
"$ 234.234,55" = 234234
"545,767$" = 545767
"765 778 00" = 765778
"765.823,888" = 765.823
I tried to use
.replace(/[^\d]/g, '');
but "$ 234.234,55" results is 23423455 and I need 234234 without the decimals. I guess I need to treat the decimals first.
And I also have cases where decimals are separated by "," or "." and can have 3 digits, ex: "1.365.823,803" or "12244.222".
In cases where I have "123.444" what leads me to know that the "." is not for decimals is that the number is never inferior to 10000.
How can I implement a function to extract these numbers?
EDIT:
I think the first step would be to remove all characters except "," or ".".
Than, we can find the decimal symbol, looking for the first symbol from the left.
If it comes after 2 digits, than we know its a decimal symbol.
If it comes after 3 digits, we look for the next symbol to see if it is different.
If it is the same than the first one is not a decimal symbol.
If it is different, than the first one is decimal.
If there's no other symbol, we know the first one is decimal because all numbers are superior to 1000, so if we have 1233.444 we know the "." is the decimals symbol.
Upvotes: 0
Views: 154
Reputation: 1352
You can simply use this
$(document).ready(function(){
myString = "CAD$764.35";
myString = myString.replace ( /[^\d.]/g, '' );
alert(myString);
});
Upvotes: 1
Reputation: 832
If I were you, I'd not try to reinvent the wheel. I suggest you a js library called numeral js which can handle the problems with the different currency and decimal formats.
For instance:
numeral("$ 234.234,55")
would output:
234.23455
Check it out for more examples.
Upvotes: 0
Reputation: 2772
If you want to get rid of the decimal part of the number and you a sure always is gonna come after a dot symbol you can use the next set of steps to remove the decimal part and get only the value.
' CAD$764.35'.split('.')[0].replace(/[^\d]/g, ''); // 764
In my opinion a better approach would be to remove all non number/dot characters from the string using replace and a regex, parse the string to a number.
To support all the cases you have, first you must analyze the string and verify which separation symbol is using and adjust the regular expression accordingly. When you use parseInt
to coarse the string to a number you don't have to care if the decimal separation symbol is ,
or .
.
parseInt('3452,90') // 3452
parseInt('3452.90') // 3452
But you must remove the other separation symbols from the string or this will cause a bug when you try to parse them.
parseInt('3,452.90') // 3
Upvotes: 1