Laureant
Laureant

Reputation: 1019

JavaScript separate currency into number value and currency symbol/name

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.

Upvotes: 0

Views: 1171

Answers (1)

TKoL
TKoL

Reputation: 13912

I'm not sure how to use regex to do this, but what I might do without regex is:

a) record the index of the first numeric character

b) record the index of the last numeric character

c) take the substring from the first to last numeric characters and convert that to a Number, Number(numerics) (you will have to remove commas between numbers for this step)

d) if the first numeric character index is 0, the currency symbol/name will be at the end of the string, after the last numeric character

e) otherwise it will be at the front of the string, before the first numeric character.


edit

you may be able to simplify the whole thing if you can be certain that what you get back as a response always contains one space that seperates the value and the currency symbol. If that were true (as it is in your examples), you could just use string.split(' ') to get an array of the two strings, and check which one is the number.

Upvotes: 0

Related Questions