2

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.

2 Answers2

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,084
  • 11
  • 68
  • 89
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,422
  • 19
  • 22