I am getting a currency value from a web service, that I would like to display in a number input (the float part) and it's currency symbol/name on a simple label that's next to the input.
Example of data that I get from the web service:
$ 1.200,05
R$ 1200.05
kr. 1,200.05
37,200.05 kr.
$300
500.0 €
You can see that the data is very mixed.
The symbol/currency name can be before or after the number value, it can have a space between the symbol and the number, or no space at all. It can also have a dot inside the currency name, that I would still like to keep (like with the danish krone: kr.)
The decimal mark can either be a '.' or a ',' and it can be followed by any number of decimals. Same with the thousand separator: it can be either a '.' or a ','
I have the following snippet to get the number value, but i'm having trouble getting the currency string part:
if (!isNaN(cost.charAt(0))) { //check whether it starts with number or string, to adjust the regex
var regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9])/
var result = regex.exec(cost);
var floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : cost.replace(/[^0-9-+]/g, "");
return floatResult;
}
else {
var regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9]+)$/igm
var result = regex.exec(cost);
var floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : cost.replace(/[^0-9-+]/g, "");
return floatResult;
}
I am using jQuery and AngularJS in my webapp, so if there's an easier method with the help of one of those, it would be nice.