Formatting numbers as floating point values in AngularJS

I need a text box where users can enter an amount. The input should be restricted to numbers only, with no special characters or decimal points. I have managed this using custom filters. However, I also need the entered number to automatically display as a float with two decimal points in the same text box. Can anyone please advise on how to achieve this using AngularJS? Here is the input text:

Answer №1

I created a custom directive to only allow float numbers as input:

.directive('floatOnly', function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue === undefined) return '';

        // Removing invalid characters
        cleanInputValue = inputValue.replace(',', '.') // converting commas to dots
          .replace(/[^\d.]/g, '') // keeping only numbers and dots
          .replace(/\./, "x") // replacing the first dot with X
          .replace(/\./g, "") // removing all other dots
          .replace(/x/, "."); // changing X back to dot
        if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
        }
        return cleanInputValue;
      });
    }
  }
});

To use this directive, insert the following code in your HTML:

<input type="text" ng-model="myFloat" float-only/>

Test snippet:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {

}]).directive('floatOnly', function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue === undefined) return '';

        // Remove forbidden characters
        cleanInputValue = inputValue.replace(',', '.') // change commas to dots
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, "."); // change X to dot
        if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
        }
        return cleanInputValue;
      });
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    Float only: <input type="text" ng-model="myFloat" float-only/>
  </div>
</div>

Try it out on JSFiddle

Test the functionality by entering different inputs into the text field

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

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

Determine whether the product is present, and if it is, verify whether the user is included in the array of objects

Whenever a button is clicked by a user, the system sends their userID along with the product ID to the query below. The goal is to validate if that specific product exists and then check if a particular userID exists within an array of objects in the sam ...

Encountering a FeathersJS Twitch OAuth 401 Unauthorized error

I'm a newcomer to FeathersJS and I've been trying to set up OAuth login with Twitch. Following the steps outlined in the Feathers documentation for setting up GitHub login OAuth, I created a Twitch OAuth application. However, when attempting to s ...

Utilize AJAX to connect to a remote domain from an extension

I am currently working on creating a Chrome extension that will utilize AJAX to fetch data from a specific webpage and then generate notifications based on the content of that page. The webpage I am targeting is a ticketing system, and my goal is to deter ...

Every time I hover, my jQuery code keeps repeating the hover effect

I am currently facing an issue that has me stumped on finding a solution. The problem arises when I hover over the .div multiple times, the animation just doesn't stop and keeps running continuously. What I aim for is to have the .hidden element fad ...

html carousel not updating in popover

I've been attempting to create a popover with a bootstrap carousel, where the carousel items are dynamically generated and appended from a script. Despite my efforts, I have successfully displayed the carousel but struggle to append the items. I' ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this: const array = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { ...

Utilize react-router-dom for conditional rendering based on button clicks

When the user types in "user" in the text box, they will be directed to the user page. If they type "admin", they will be redirected to the admin page. This code belongs to me. constructor(props) { super(props); this.state = { userType : 0 ...

Convert Excel Spreadsheet data into an interactive HTML chart in real time

Looking for a solution to update an Excel spreadsheet monthly and display it on a Blackberry browser? I've already built a website with all the spreadsheet information using HTML lists and CSS for charts. I need help loading a new spreadsheet into th ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

What is the best way to interweave my objects within this tree using recursion?

I am working on creating a new function called customAdd() that will build a nested tree structure like the one shown below: let obj = [] let obj1 = { key: "detail1Tests", id: "94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e" } ...

Troubleshooting Issue with Node.js and Postman: Error encountered while attempting to

Consider the following code snippet: const fs = require('fs'); const express = require('express'); const app = express(); const bodyParser = require('body-parser') // using middleware app.use(express.json()); app.use(bodyPar ...

Is there a way to narrow down Drive API list results based on a specific domain that has write permission?

I am currently working on retrieving a list of files from the drive API using a service account, with permissions granted to a specific domain for editing. While I have successfully implemented this feature for individual emails, I am facing a challenge in ...

Having trouble establishing a connection between Node.js and SQL Server using Tedious library

When attempting to connect to a local SQL Server instance using Node.js and Tedioius, I encounter the following error: { [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED] name: 'ConnectionError', message: 'Failed ...

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...

Display a substitute image if there is no internet connection available to load the Google Map Canvas

I have a WebApp that runs locally, but it's possible that users may not always have access to 3G/WiFi when using the app. This means that the Google Map will not load without an internet connection since it requires the web API. In order to provide a ...