Home > Blockchain >  Format string as currency REGEX
Format string as currency REGEX

Time:08-06

I'm currently trying to transform some data before displaying on NetSuite server side with suitescript 1.

Unfortunately, can't use toLocaleString.

Data Output Expected
1000 1000USD 1,000.00 USD
1 1EUR 1.00 EUR
2000000.1 2000000.1GBD 2,000,000.10 GBD

Any idea how I can accomplish that? mostly looking to do it with a simple function like this one

fuction formatThis(str){
  return String(str).replace(/(.)(?=(\d{3}) $)/g, '$1,');
}

CodePudding user response:

If your version of NetSuite is 2.0, you may only have access to ECMA Script 5.1

Here is a function that would do the formatting without using ECMAScript 2015 features. It takes a second argument for the currency. I don't see that anywhere in your examples on the input side:

function format(str, currency) {
    return (str   ".00")
        .replace(/(\.\d)\.00/, "$10")
        .replace(/\. (\d{0,2}).*/, ".$1 "   currency)
        .replace(/\d(?=(\d{3}) \b)/g, "$&,");
}

// Examples:
console.log(format("1000", "USD"));
console.log(format("1", "EUR"));
console.log(format("2000000.1", "GBD"));

CodePudding user response:

You can extract the leading number, and format the currency using a bunch of regexes:

function formatCurrency(str) {
  return str.replace(/^[0-9\.] /, function(m) { // extract the leading number
    return parseInt(Number(m) * 100, 10)        // convert the number to cents
      .toString()                 // convert back to string
      .replace(/(..)$/, '.$1')    // add dot, e.g. restore currency from cents
      .replace(/(.)(.{12})$/, '$1,$2') // add comma to billion
      .replace(/(.)(.{9})$/, '$1,$2')  // add comma to million
      .replace(/(.)(.{6})$/, '$1,$2')  // add comma to thousand
        ' ';
  });
}

[
  '1000USD',
  '999CHF',
  '1EUR',
  '2000000.1GBD'
].forEach(str => {
  console.log(str   ' => '   formatCurrency(str));
});

Output:

1000USD => 1,000.00 USD
999CHF => 999.00 CHF
1EUR => 1.00 EUR
2000000.1GBD => 2,000,000.10 GBD
  • Related