How to round up or down a number using DecimalPipe in Angular

Viewed 11341

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?

1 Answers
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

Related