Angular can help you easily convert numbers into a money format

I need assistance in converting a number to Indian currency format.

Currently, I have attempted the following: http://plnkr.co/edit/lVJGXyuX0BMvB9QUL5zS?p=preview

function formatMoney(credits) {

    console.log(credits+'credits');
    var lastThree = credits.substring(credits.length-3);
    // var lastThree = credits.slice(-2);
    var otherNumbers = credits.substring(0,credits.length-3);
    console.log(otherNumbers+'otherNumbers');
    if(otherNumbers !== '')
        lastThree = ',' + lastThree;
    var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
    return res;
  }

function formatNumber(num) {
    var n1, n2;
    num = (Math.round(num * 100) / 100) + '' || '';
    n1 = num.split('.');
    n2 = n1[1] || null;
    n1 = n1[0].replace(/(\d)(?=(\d\d)+\d$)/g, ",");
    num = n2 ? n1 + '.' + n2 : n1;
    return num;
  }

I am specifically looking to format the number as Indian currency.

For example:

1,000
10,000
1,00,000
10,00,000

The result obtained with the function formatMoney() is: 1,0,0,000

The result obtained with the function formatNumber() is: 1,000 but on adding a 0, it becomes NaN0

I would appreciate any guidance on where I might be going wrong in my approach.

Answer №1

AngularJS provides filters for performing these types of tasks, such as the currency filter:

I have revised your code by removing the formatting functions and replacing them with the currency filter along with the Rupee symbol for Indian currency. Hopefully, this resolves your issue.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  
  $scope.change=function($event, money){
      $scope.money = qwerty;
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7819161f0d14190a56120b3849564a5600">[email protected]</a>" src="https://code.angularjs.org/1.2.20/angular.js" data-semver="1.2.20"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <input  ng-keypress="change($event, money)" type="text" ng-model='money' >
    <pre>{{money | currency : "&#8377;" }}</pre>
  </body>

</html>

Answer №2

Angular is not necessary for this task because there is a core JavaScript API called Intl that can be used.

var number = 2453413.70;

console.log(new Intl.NumberFormat('en-IN', { style: "currency", currency: "INR" }).format(number));

If you prefer not to display the currency symbol, you can do it like this:

console.log(new Intl.NumberFormat('en-IN').format(number));

Answer №3

Utilize the $filter service directly within your controller or view.

var myApp = angular.module('myApp', []);
myApp.controller('CalcCtrl', function ($scope, $filter) {
    $scope.num = 122212111221121212;
    $scope.filtered = $filter('currency')($scope.num);
    alert($scope.filtered)
});

Remember, the $filter service can be easily extended as well.

myApp.filter('customCurrency', function() { 

    return function(input, symbol, place) {

    // Ensure that we are working with a number
    if(isNaN(input)) {
      return input;
    } else {

      // Check if optional parameters are passed, if not, use the defaults
      var symbol = symbol || 'EUROS';
      var place = place === undefined ? true : place;

      // Perform the operation to set the symbol in the right location
      if( place === true) {
        return symbol + input;
      } else {
        return input + symbol;
      }

    }
  }

});

myApp.controller('CalcCtrl', function ($scope, $filter) {
    $scope.num = 122212111221121212;
    $scope.filtered = $filter('customCurrency')($scope.num);
});

View Demo

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

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

Looking for a way to sort through data using the current time as a filter

In my possession is an object presented below: const user = { id: 3, name: "Clark Kent", mobileNumber: "1234567892", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385d40595548545d674d4b ...

When the window is fully loaded, JavaScript executes

Can someone help me set up this script to start running when the page loads? I want the vat field to automatically show up if the company name has been entered. Thank you! //--></script> <script type="text/javascript>//-- $('.colorbox ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

Error in ReactJs production code: ReferenceError - the process is undefined

Having some trouble with my ReactJs production code not recognizing environment variables. The error message reads: Uncaught ReferenceError: process is not defined <anonymous> webpack://testProject/./src/agent.js?:9 js http://localhost:8080/s ...

Creating a series of text messages for Push Notifications using FCM in conjunction with Ionic 1. Multiple lines of

I've been attempting to send push notifications with multiline text messages. I've experimented with various techniques such as using setBigStyle in FCMService.java, HTML.fromHTML, and others, but haven't been successful in getting the messa ...

Issue: ngModel: Unassignable Value

I am currently working on a piece of code that dynamically generates a drop-down list. My goal is to set the selected value using ng-repeat. In order to achieve this, I have implemented a function in ng-model. However, I am encountering an issue with the f ...

Utilizing JSON data to generate an HTML webpage showcasing a collection of community districts through the power of JavaScript

As a beginner in javascript, I am working with a JSON file that contains an array of objects. Each object includes two properties: a borough and mappings. Mappings have two sub-properties called macro and neighborhoods. The macro represents a larger neighb ...

In order to verify the dynamic components within the table

I need assistance with validating dynamically created textareas. In the code below, I am able to validate only the first row but struggling to do so for the second row. How can I get all the row values validated? Thank you in advance. To generate dynamic ...

Instructions for activating column resizing in MUI DataGrid

Is there a way to enable column resizing for users in MUI DataGrid? It's enabled by default on XGrid, but I would like to enable it on Datagrid as well. Any assistance is appreciated. <DataGrid className={classes.table} ...

Once an ng-repeat is completed, I must extract and retrieve the 'id' of a specific element

Is it possible to retrieve the 'id' of the comment I'm replying to and save it for an Ajax call? I can easily access other data with ng-model, but using value="{{this.id}}" in a hidden input doesn't seem to work like in JQuery. <scr ...

Unable to delete a row from a dynamically generated table using jQuery

I am currently working on a project that involves creating a table based on results from a servlet. The table includes checkboxes, and when a checkbox is checked, a button at the bottom of the table should appear. This button calls a remove function to del ...

Is your custom login form in Web2py not submitting properly?

My attempt to customize the login form for web2py has hit a roadblock. Despite adding the necessary fields and submit button, nothing seems to be happening. Here's what the code in the form's view looks like: {{include 'web2py_ajax.html&apo ...

What are the best practices for incorporating React state into a dynamic filter component?

I am working on a filter component that will help me display specific data to the DOM based on user-selected filters. However, I am facing a dilemma regarding how to maintain state without resetting the filter input and how to render the filtered data with ...

Tips for regularly retrieving information from a psql table

I have a scenario where I am retrieving data from a psql table and converting it into a JSON array to be used for displaying a time series chart using JavaScript. The data that is passed needs to be in the form of an array. Since the data in the table get ...

A loop that iterates through only the initial element of an array

When trying to call in the array values using the code snippet below, I encountered an issue. Upon clicking, I am able to successfully retrieve the first material in the array, but then it stops looping through the rest of the materials. Can someone plea ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

Encountering issues while running the npm build command due to exporting async functions in React

In my React project, I am utilizing async functions and have created a file named apiRequest.js structured like this: const axios = require('axios'); const serverURL = "http://localhost:8080" getInfo = async function ({email}) { try { r ...

The EJS template on the Express app is encountering an issue: it is unable to find the view "/id" within the views directory located at "/home/USER/Desktop/scholarship-app/views"

When attempting to render the request URL for an ID in my Express app, I encountered the following error: Error: Failed to find view "/id" in views directory "/home/USER/Desktop/scholarship-app/views" Here is a portion of my Express app code: app.get(&a ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...