如何在 Angular 中使用 DecimalPipe 向上或向下舍入数字

nia*_*ian 14 typescript angular

我认为如何DecimalPipe在 Angular 中使用向上或向下舍入一个数字,默认情况下会舍入一个数字,例如:
DecimalPipe

 Rounding({{value | number:'1.0-2'}})
 1.234 => 1.23
 1.235 => 1.24
Run Code Online (Sandbox Code Playgroud)

就我而言,我想向上/向下舍入一个数字,例如:

 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
Run Code Online (Sandbox Code Playgroud)

我怎样才能直接使用DecimalPipe

小智 5

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

TS游乐场

用法:

围捕{{value | toFixed:2:"up"}}

1.234 => 1.24

1.235 => 1.24

向下舍入{{value | toFixed:2:"down"}}

1.234 => 1.23

1.235 => 1.23