periback2
periback2

Reputation: 1469

How to get currency of a string in javascript

I need help to handle the following situation: I have some values that I need to sum in a page, but the fields of these values are created dynamically (so are the ids of these fields).

The values can be displayed in different format (depending on the currency or decimal places), i.e.: R$20.000,2 (1 decimal place) or US$20.000,18 (2 decimal places) or €20,000.180 (3 decimal places and imperial system).

What did I do until now:

Since the fields are created dynamically, I added a css class to the style of that fields (they're generated through a for each loop), then I use a javascript prototype class that I created to convert string to float (if I pass R$20.000,02 or R$20,000.02 and it returns 20000.02). the following code iterates in all fields generated in the page that I need to sum.

<script>
    var sum = 0;
    jQuery(".countTotalEffectiveMonth").each(function(){
        sum += localeUtils.s2f(jQuery(this).text().replace("R$",""));
        jQuery("#ScenarioCurrentYearSavings").text(sum);

        })
    alert(sum);

</script>

The problem:

1: I hardcoded the currency ("R$","") (to remove it from the string and make calculation). any ideas about how can I do that? I tried to use regex, but I failed :(. I could only remove the currency using this regex (/[^0-9-]/g), but I didn't know how to store it so that I could concatenate it in the end of the sum.

UPDATE:

By following Paul S.'s approach, I did this:

var val;
var re = /^([a-z]+)([^\d])([\d.,]+)$/i;
var m;
jQuery(".countTotalEffectiveMonth").each(function(){
    m = jQuery(this).text();
    val = re.exec(m);
    val += val[3].replace(/,/g, '');
    alert(val[1]+val[3]);
    jQuery("#ScenarioCurrentYearSavings").text(val[1]+val[3]);

});

It says that val is null, but I printed m just before executing val = re.exec(m); and it prints a number like this R$91,67, but them I receive TypeError: val is null.

Can you see what is wrong?

Upvotes: 1

Views: 3323

Answers (1)

Paul S.
Paul S.

Reputation: 66394

What about a regexp that looks like this

var re = /^([a-z]+)([^\d])([\d.,]+)$/i,
    m;
m = re.exec('US$20.000,18'); // ["US$20.000,18", "US", "$", "20.000,18"]
m = re.exec('R$20,000.02');  // [ "R$20,000.02",  "R", "$", "20,000.02"]

Then m[3] is the numeric value, and this can be converted to a Number using more logic, e.g. if it's in the form x,xxx.xx

var int = +m[3].replace(/,/g, ''); // 20000.02

Upvotes: 1

Related Questions