17

How to round up or down a number using DecimalPipe in Angular
I think, DecimalPipe will round a number by default, like:

 Rounding({{value | number:'1.0-2'}})
 1.234 => 1.23
 1.235 => 1.24

In my case, I'd like to round up/down a number, like:

 Rounding up({{value | number:'1.0-2'}})
 1.234 => 1.24
 1.235 => 1.24

 Rounding down({{value | number:'1.0-2'}})
 1.234 => 1.23
 1.235 => 1.23

How can I achieve this directly using DecimalPipe?

Roy
  • 7,811
  • 4
  • 24
  • 47
niaomingjian
  • 3,472
  • 8
  • 43
  • 78
  • 4
    Now my downvote, but why not just use base JavaScript's `floor()` and `ceil()` functions inside your controller? – Tim Biegeleisen Aug 07 '17 at 06:27
  • @TimBiegeleisen Since angular provides the pipe to format a number as text, I think it's a good idea to handle the fractions together in the way we want. – niaomingjian Aug 07 '17 at 06:42
  • It looks like the [`DecimalPipe`](https://angular.io/api/common/DecimalPipe) doesn't have this option, you can check the [source code](https://github.com/angular/angular/blob/4.3.3/packages/common/src/pipes/number_pipe.ts#L61-L96) if you want. I think @TimBiegeleisen suggested a good solution if he wants to post it as an answer - or you could create a custom pipe of your own to do this. – 0mpurdy Aug 07 '17 at 07:15
  • 3
    You can build your own pipe: [like here](http://blog.bastien-donjon.fr/round-number-angular-2-pipe/) – Malik Shahzad Aug 07 '17 at 07:18
  • just add/less .005 to your number before pipe – Eliseo Jun 28 '21 at 19:50

1 Answers1

4
import {Pipe, PipeTransform} from '@angular/core';

enum Direction {
    UP = 'up',
    DOWN = 'down'
}

@Pipe({name: 'toFixed'})
export class ToFixedPipe implements PipeTransform {
    /**
     *
     * @param value - some number
     * @param digits - number of digits after the decimal point
     * @param dir - round up or down (floor/ceil)
     * @returns {string} formatted number with a fixed number of digits after the decimal point
     */
    transform(value: number, digits: number = 0, dir: Direction = Direction.DOWN): number {
        const round = dir === Direction.DOWN ? Math.floor : Math.ceil;
        return round(value * (10 ** digits)) / (10 ** digits);
    }
}

TS Playground

Usage:

Rounding up {{value | toFixed:2:"up"}}

1.234 => 1.24

1.235 => 1.24

Rounding down {{value | toFixed:2:"down"}}

1.234 => 1.23

1.235 => 1.23