Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 742
niaomingjian Avatar asked Aug 07 '17 06:08

niaomingjian


People also ask

What is the default value of minIntegerDigits while using the DecimalPipe?

minIntegerDigits : The minimum number of integer digits before the decimal point. Default is 1.


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

like image 156
Alexander Alexandrov Avatar answered Oct 21 '22 03:10

Alexander Alexandrov