Search code examples
javascriptangularjsecma

Display number in brackets using toLocaleString for negative values


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.


Solution

  • 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;