How to format a number value in AngularJS ui-grid cell to two decimal?
Asked Answered
H

3

10

I'm using Angularjs ui-grid and using the default settings, the question is how can I format the numbers to two decimal?

enter image description here

Hedvah answered 21/5, 2015 at 19:26 Comment(0)
V
28

You can use the columnDefs cellFilter option:

columnDefs: [
  {
    field: 'name',
    cellFilter: 'number: 2'
  }
]
Vizierate answered 21/5, 2015 at 19:49 Comment(2)
How to display 0 to 0.00 in ui-grid ?Izabel
When I try to export my ui-grid as a pdf, the numbers still show multiple decimal points. Do you know of a way I can export my uigrid as a pdf with the data only showing two decimal?Snowplow
D
0

Via user defined filter function:

http://fiddle.jshell.net/r8yj2jgw/2/

 cellFilter:'formatNumber:2'

.

app.filter('formatNumber', function() {  
      return function(input, decimalPlaces) {          
       if(isNaN(input))
            return input;
         else {
          return input.toFixed(decimalPlaces);
        }
      };
    });
Diaspora answered 15/7, 2016 at 1:19 Comment(0)
P
-1

You're looking for .toFixed(2).

Use cases:
var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346': note rounding, no fractional part
numObj.toFixed(1);      // Returns '12345.7': note rounding
numObj.toFixed(6);      // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
-2.34.toFixed(1);       // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1);     // Returns '-2.3' (...unless you use parentheses)
Pruinose answered 21/5, 2015 at 19:52 Comment(1)
The question specifically asked, how to format a number value in Angular ui-grid, which requires a custom filter. While this answer is technically correct for general JavaScript usage, it is not an appropriate answer for this question.Cherrylchersonese

© 2022 - 2024 — McMap. All rights reserved.