Angular is displaying parentheses for negative numbers

When working on my template, I encounter a math issue where the result sometimes turns out to be a negative number. The problem is that when this happens, it displays the number within parentheses. How can I fix this using Angular 1.2?

This is my controller:

$scope.totalToReceive = totalToReceive;
$scope.discountedTotal = discount;
$scope.antecipatedTotal = antecipatedTotal;
$scope.totalReceived = totalToReceive - discount + antecipatedTotal;

Here is my template:

<li>
    <span class="big-number"><span>R$</span> {{ totalReceived | currency: ""}}</span>
</li>

Update: I attempted to create my own filter, but unfortunately it did not work as intended.

.filter('numeric', function(){
return function (value) {
if (value < 0) {
value = '-' + Math.abs(value) + '';
}
}
})

Answer №1

Solution discovered! It's actually quite simple. All that was needed was to create a new filter:

.filter('newCustomCurrency', ['$filter', function($filter){
return function (amount, currencySymbol) {
    var currency = $filter('currency');

    if(amount < 0) {
        return currency(amount, currencySymbol).replace("(", "-").replace(")", "");
    }
}
}])

Here is how it can be used in the template:

<span class="big-number"><span>€</span> {{ totalAmount | newCustomCurrency: ""}}</span>

Answer №2

I encountered a similar problem and here is how I resolved it.

To tackle the issue, I devised a method within my Angular service so that I could easily invoke it whenever necessary.

formatNegativeVal(value: any){
  if(value.substring(0,1) === '-'){
    console.log('valusss ', value)
    return "(" + (value.replace(/-/g, '')) + ")"
  }else{
    return value;
  }
}

Afterwards, I simply created another method in the specific component where I intended to utilize the aforementioned logic.

formatNegativeVal(value: any){
    return this.common.formatNegativeVal(value);
  }

Lastly, I invoked the newly created function and passed the entire currency value on the HTML page.

<ng-container matColumnDef="credit_balance">
   <th mat-header-cell *matHeaderCellDef mat-sort-header> Balance Credit </th>
   <td mat-cell *matCellDef="let element"> 
      {{formatNegativeVal(element?.credit_balance | currency : configs?.money_symbol 
      + ' ':'symbol':'1.0-0')}} 
   </td>
</ng-container>

Answer №3

To format numbers as currency in JavaScript, you can utilize the toLocaleString method and specify the "currencySign" option:

const num = 4567.89;
console.log(num.toLocaleString('en-US', { 
  style: 'currency', 
  currency: 'USD',
  currencySign: 'standard' 
}));

// $4,567.89

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

determine if the req.params parameter is void on an express route

Hi everyone, I'm a beginner with node and express and could really use some guidance. I am currently attempting to create a get request that checks if the req.params.address_line is empty, and then performs an action based on that condition. However, ...

Experimenting with an Angular controller while maintaining its dependency integrity without the use

After spending 48 hours scouring the internet for answers to my question without success, I find myself seeking help here. The controller I am trying to test is as follows: (function () { "use strict"; angular .module("productManagement" ...

Having trouble getting the ReactJS AXIOS post function to work properly?

Error in console: [1]: https://i.sstatic.net/xOfUV.png issue with axios request .post("https://bootcamp-2022.devtest.ge/api/application", { token: "7e475dfc-0daa-4108-81c8-d6c62a3df4ca", first_name: JSON.parse(localStorage.ge ...

How can I avoid using the appendTo method in jQuery?

There seems to be an issue in my HTML code, could you please take a look at the code snippet below: HTML: <div class="agent_select_wrap"> <select name="menu-114" class="wpcf7-form-control wpcf7-select" aria-invalid="false"> <op ...

What are the steps to deploy Next JS?

For my latest project, I dived into the world of Next JS with Tailwind CSS and decided to use "next build" to compile it. However, after running the command, it generated a folder named ".next", but surprisingly no .html files were found within. Coming fr ...

Teach me the steps in a promise chain to send a response and conclude the flow of the promise

Whenever I run the code below, I encounter this particular error message: Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client when result === null. 'use strict' const HttpStatus = require(&a ...

Express req.files returns null when using jQuery FormData

For client side functionality, I am utilizing Bootstrap and jQuery. On the server side, my technology stack includes node.js and express. The form structure is displayed below: <form id="signupform" action=""> <h2&g ...

Can you please explain the concept of straightforward UI routes to me?

I recently discovered that ui-routes are more powerful and advantageous than ngRoutes. In an effort to learn more about the ui-routing feature, I started studying from http://www.ng-newsletter.com/posts/angular-ui-router.html. However, I found it challengi ...

Displaying over 20 columns of data in a webpage can be achieved effortlessly by utilizing the power of jQuery DataTables in conjunction

Hey everyone, I'm currently facing a challenge in displaying more than 20 columns using datatables on a single webpage. My tech stack includes MySQL, jQuery datatables, and HTML. This is my MySQL query: select LOT_LOCATION, `Zone Attribute`, a.LOTID, ...

Vue re-evaluating all properties when an object is modified

Is Vue smart enough to know when an object property is changed and only recompute the computed properties related to that specific property? Or does it recalculate all computed properties associated with the object every time a single property changes? If ...

Unknown passport authentication method

I'm currently delving into a tutorial on building an authentication system using passport in Nodejs. The guide can be found here. My focus right now is on getting the signup form to function properly, but it keeps throwing this error: Error: Unknown ...

What is the process for sending a POST request from a React app to a Node.js Express server?

I watched a tutorial video on resolving the CORS issue, which worked well for GET requests. However, I encountered an issue when attempting to send a POST request. Unfortunately, I do not have control over the third-party API and cannot make any changes to ...

Combining RxJS Promises (transferring information)

As a newcomer to Rx, I am struggling to locate documentation on how to compose promises where the data from the first promise is passed into the second one and so forth. Here are three basic promises with asynchronous operations involving previous data: ...

What is the best way to conceal links within a repeater that lacks any extension?

In my ASP.NET application, I have download links for .pdf files displayed within a repeater. However, I would like to hide links that do not have the .pdf file extension. JavaScript // get file extensions var fileURL = $('hl_download').a ...

I have a JSON file saved on my desktop that I would like to incorporate into my JavaScript code. Any suggestions on how to efficiently achieve this integration

Here is a code snippet that I have been experimenting with: const dictionary = require('dictionary.json'); //(with file path) console.log(dictionary); ...

Connect your sails.js application to a designated IP address

Currently, I am working on a Nodejs project that utilizes the sails.js mvc framework. As I prepare to deploy it, one of the requirements is to bind it to a different IP address. I am curious if there is a way within sails.js to accomplish this task. Whic ...

Which medium is the optimal choice for file manipulation in Node.js and JavaScript?

Is there a simple way for JavaScript to receive incoming data from Node.js that was obtained from an external server? I've been searching for a solution to this problem for days now. Here's my current approach: I plan to have both the server-sid ...

avoiding less than or greater than symbols in JavaScript

I'm encountering an issue while attempting to escape certain code. Essentially, I need to escape "<" and ">" but have them display as "<" and "> in my #output div. At the moment, they show up as "&lt;" and "&gt;" on the page. This ...

What is the method for running code once the $digest cycle has finished?

I have created a sortable list in my Angular Controller that gets populated with data. This list includes an extra element with controls that can also be dragged. My goal is to ensure that the extra element remains in place after the $digest cycle runs, s ...

There was a DOMException in Angular because the transaction is not active when trying to execute 'getAll' on 'IDBObjectStore'

private get ctxMessage() { const messageTransaction = this.db.transaction('messages', 'readwrite'); const messageStore = messageTransaction.objectStore('messages'); return { messageTransaction, messageStore }; } ...