Limit AngularJS input ng-model to only accept two decimal places or two digits

My question involves an input field with a default value set in the controller and passed as 'val:1.81' using ng-model. This input must only accept numeric values (type: number). Through Angular filters, I have managed to display only two decimal places on the next line using the 'number 2' filter. Additionally, I am looking to include buttons that will allow users to add or subtract '0.01', similar to a counter input.

Is there a way to ensure that the input is filtered to display only two decimals? I ask this because when summing by clicking the button, sometimes the input displays something like '1.8800000000000001'.

Original JS Bin

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

app.controller("mainCtrl", function($scope)
{
  $scope.val = 1.80;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
  <br/><br/>
  <div>
    <span style="color: red">Val input:</span>
  <input type="number" ng-model="val"/>
  <button ng-click="val = val - 0.01">-0.01</button>
  <button ng-click="val = val + 0.01">+0.01</button>
  </div>
  <div>Val: {{val | number:2}}</div>
  
  <hr>
  
  Val2 (val + 20): {{ val2 = val + 20 | number:2 }}
  
  <hr>
  
  Val2 input:
  <input type="number" ng-model="val2"/>
  
</div>

Answer №1

An unconventional solution could involve monitoring changes in the $scope.val property and automatically rounding the number to 2 decimal places.

To implement this approach, you simply need to adjust your controller like so:

app.controller("mainCtrl", function($scope)
{
    $scope.val = 1.80;
    $scope.$watch(
      function(scope) { 
        return scope.val; 
      },
      function(num) {
        $scope.val = Math.round(num * 100) / 100;
      }
  );
});

This technique ensures that whenever a change occurs, the value is updated with the rounded 2-digit version. No additional modifications to the HTML or templates are required.

View a demonstration in JS Bin: http://jsbin.com/viyixofova/1/ (note that only the first input field has the rounding feature).

Answer №2

For more information on precision handling for floats, you can visit this link.

In your specific case, you can achieve the desired result with code similar to this:

$scope.val = parseFloat(($scope.val - 0.01).toFixed(2));

Another option is to use .toPrecision(3) instead.

Regarding filtering user input to two decimal places, it is recommended to monitor changes in the value and round as necessary, as suggested by @alesc.

It is also advisable to keep the logic in the controller for better organization:

$scope.increment = function(increment) {
    $scope.val = parseFloat(($scope.val + increment).toFixed(2));
};

Then, you can simply call the function in the HTML like this:

<button ng-click="increment(-0.01)">-0.01</button>
<button ng-click="increment(0.01)">0.01</button>

Answer №3

Thank you for the assistance, I ultimately decided to utilize this link: http://jsbin.com/sufida/7/edit

One final inquiry, is there a method to streamline the increment and decrement functions for any ng-model input value without redundant use of parseFloat?

Appreciate your help once more

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

Step-by-step guide on making a table of objects using JavaScript

As a new React user venturing into website creation, our goal is to design a table where each row outlines various details about an object. We aim to achieve rows similar to the example provided here. In my view, our strategy should involve generating a l ...

Can you explain the distinction between employing express.urlencoded() with extended set to true as opposed to setting it to false along with performing manual JSON stringify/parse calls?

Within my NodeJS/Express server, I am faced with the decision of setting extended to either true or false for the urlencoded middleware: app.use(express.urlencoded({ extended: true/false })); I have come to understand that when set to false, it signifies ...

React Native bug: For Loop displaying only the initial element in the Array

I'm currently working on a function that is meant to iterate through 20 elements of an array called smn to display the elements that meet a specific condition. However, with my current code, I am only able to display the first element in the array: ...

Repeatedly iterates through the JSON properties that have been grouped together

https://jsfiddle.net/MauroBros/f1j0qepm/28/#&togetherjs=qedN5gf7SF Upon examining a JSON object, the structure is as follows: var values = [ {"aname":"account1", "pname":"pname1", "vname":"vname1& ...

Creating a dynamic category menu using angularJS

I'm struggling with the logic behind creating a category menu using AngularJS I need to display all categories with a parent category id of 0. Once that is done, I want to display all subcategories that belong to each parent category. The final categ ...

Tips for effortlessly sending data and executing a link in a single click

I need to send latitude and longitude data to search it on Google Maps. The data needs to be retrieved from a database, but I'm struggling to figure out how to do it with just one click. Here is the code snippet: <?php $con = mysqli_connect("loc ...

Slide both divs simultaneously from left to right

Is there a way to simultaneously hide and show div elements, without having to wait for the effect to take place? Here is my current code: $('a').on('click', function(){ var div_hide = $(this).parent(); var div_show = $(this). ...

Empty the localStorage when terminating the IE process using the Task Manager

Utilizing HTML5 localStorage to keep track of my application session has been a useful feature. Here is a snippet of the code I am currently using: if(typeof(Storage)!=="undefined") { if(sessionStorage.lastname=="Smith") { alert("Your ses ...

The Angular function fails to execute when clicked

I am trying to trigger a new page launch when a cube is clicked using Angular. Unfortunately, my current code doesn't seem to be working as expected and nothing happens when I click the cubes. This makes me wonder if there is something wrong with my i ...

Remove any overlapping datetime values from a JavaScript array of objects

Is there a way to efficiently remove any overlaps between the start and end times (moment.js) in a given array of objects? [{ start: moment("2019-03-23T15:55:00.000"), end: moment("2019-03-23T16:55:00.000")}, { start: moment("2019-03-23T14:40:00.000"), e ...

Blend the power of Dynamic classes with data binders in Vue.js

Recently, I've been working on a v-for loop in HTML that looks like this: <ul v-for="(item, index) in openweathermap.list"> <li>{{item.dt_txt}}</li> <li>{{item.weather[0].description}}</li> <li>{{item.w ...

Vercel enables faster PAAPI transactions through Edge Caching

When working on a Nextjs site hosted on Vercel and making a call to Amazon's paapi, it's important to keep in mind the limitations imposed by Amazon on the number of transactions allowed per second and per day. The approach I'm taking involv ...

Modify the disabled attribute in an input element with a button click in Vue.js 2.x

With a loop generating multiple rows, each containing its own 'input' with description and action buttons, including an edit button that toggles the 'disabled' attribute. I'm struggling to figure out how to achieve this. I believe ...

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

Having trouble loading Three.js in JavaScript file using npm install?

I am encountering a problem when trying to include Three.js in my JavaScript file without using the HTML script element. The error message I receive is "Uncaught SyntaxError: Cannot use import statement outside a module". Although my Three.js code runs suc ...

Error message: "Unfortunately, the requested page cannot be found when attempting to reload

After successfully deploying my Angular app to Firebase and being able to access the sign-in page without any issues, I encountered an error upon reloading the page: The file does not exist and there was no index.html found in the current directory or 404 ...

What is the best way to send a distinct identifier using JavaScript or PHP?

I am looking for a way to replace "INSERT+ORDER+ID" with a unique ID when a user clicks on our "Request Information" button to improve visitor tracking. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated, thank you ...

What could be the reason for the page scrolling upwards when clicking on href="#"?

I am encountering an issue with a hyperlink <a href="#" id="someID">Link</a> that is located further down the page. This link is used to trigger an Ajax request, but whenever it is clicked, the page automatically scrolls back to the top. I have ...

What is the reason behind jQuery's .html("abc") only providing temporary insertion?

I have come across an issue with an HTML button that triggers a function. Whenever the button is clicked, a div is inserted but it only appears for a brief moment before disappearing both visually and in the HTML tree. function openBox () { $( '#0&a ...

AngularJS interpreting HTML tags as strings

Within the product description, there is a tag <ul> <li>..</li> </ul>. I attempted to utilize the ngSanitize dependency, but it did not have the desired effect. I also experimented with ng-bind-html and $sce.trustAsHtml(), however, ...