3

I have been trying to change the numbers in AngularJS application according to the countries and used .toLocaleString function over entire application using below function

numberValueTransformation(value) {
    if (value === 0 || value === undefined) {
      return 0;
    }
    const currencyLocale = this.UserPreferences.getCountryLocale().replace(/fr-FR/g, 'de-DE');
    const currencyCode = this.UserPreferences.getCountryCode();
    return Number(value).toLocaleString(currencyLocale, {
      // style: 'currency',
      currency: currencyCode,
      minimumFractionDigits: 2
    });
}

The above function works perfectly fine but I have a requirement to show the negative values in brackets over whole application. Can we modify .toLocaleString to get the negative values in brackets or do I need to change in the entire application manually? I get the value as $123456689. But if a negative value i get -$123456789, but here i want the value as ($123456789) <--- brackets represents minus.

3 Answers3

4

Instead of directly returning the result, you can wire up the check yourself. Do the conversion on a positive number, if instead the original value is less then 0 then wrap in brackets.:

var absValue = Math.abs(value);
var returnString = Number(absValue).toLocaleString(currencyLocale, {
    // style: 'currency',
    currency: currencyCode,
    minimumFractionDigits: 2
});

return value < 0 ? '(' + returnString + ')' : returnString;
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
3

You can use .toLocaleString function directly as follows:

function numberValueTransformation(value) {

    if (value === null || value === undefined) {
      return 'some special value like N/A';
    }

    const currencyLocale = this.UserPreferences.getCountryLocale().replace(/fr-FR/g, 'de-DE');
    const currencyCode = this.UserPreferences.getCountryCode();

    return Number(value).toLocaleString(currencyLocale, {
      style: 'currency',
      currency: currencyCode,
      currencySign: 'accounting', // this is the key
      minimumFractionDigits: 2
    });
}
0

For this maybe look at the numbro.js library https://numbrojs.com/ There is a feature to format negative values in brackets as requested. The code would work like this

console.log(
numbro(-123456.78).formatCurrency({
    thousandSeparated: true,
    mantissa: 2,
    negative: "parenthesis" // This does what you want
}))
<script src="https://cdn.jsdelivr.net/npm/numbro@2.3.1/dist/numbro.min.js"></script>
There are lots of other formatting options too see https://numbrojs.com/format.html#currency
James Mudd
  • 1,816
  • 1
  • 20
  • 25