oezix
oezix

Reputation: 109

Better solution than Globalize.currencyParser?

I am using Globalize for jQuery and am searching for a solution to convert number with currency to a number without the currency symbol.

Globalize has a function Globalize.currencyParser, but in v1.1.1 its still empty, so I tried to convert with

Globalize(“fr”).numberParser()(“-10 000,99 €”)

but it became 10000,99 and not -10000,99.

In function numberParse

if ( prefix === negativePrefix && suffix === negativeSuffix ) { number *= -1; }

the number will not convert to negative, because suffix !== negativeSuffix. So, I decided to solve my problem with a regex

( /^([^0-9]*)(([0-9,\'\٬\.\s]*[0-9]+)(,٫\.[0-9]+)?)([^0-9]*)$/ )

but I'd prefer a solution with Globalize.currencyParser. Thoughts?

Upvotes: 1

Views: 83

Answers (2)

oezix
oezix

Reputation: 109

i wrote a little function im my .js file

function getNumberAndCurrency(number_with_currency) {
  var numberNumberRe = ( /^([^0-9]*)(([0-9,\'\٬\.\s]*[0-9]+)(,٫\.[0-9]+)?)([^0-9]*)$/ );
  var match_array = numberNumberRe.exec(number_with_currency);

  if ('' == match_array[5]) {
    if ('-' == match_array[1].charAt(0)) {
      var currency = match_array[1].slice(1);
      var number = '-' + match_array[2];
    } else {
      var currency = match_array[1];
      var number = match_array[2];
    }
  } else {
    var currency = match_array[5];
    var number = match_array[1] + match_array[2];
  }

  return [number, currency];
}

this work fine in "en", "de" and "fr" locale with several currencies

Upvotes: 0

Rafael Xavier
Rafael Xavier

Reputation: 2889

The ideal solution would be using .currencyParser(), but it hasn't been implemented by Globalize yet: #364 (the empty fn is definitely a bug). If you want to contribute the parser, it will be welcome and I can incorporate it to the library.

In the meantime, there's unfortunately nothing to do except using hacks . One would be to trim the Euro currency from the String, then parse the resulting number.

// Ugly hack 😭😭😭
Globalize('fr').parseNumber('-1 000 000,00 €'.replace(/€/, '').trim())
// > -1000000 

```

Upvotes: 0

Related Questions