網站搜尋

typescript - 如何在 Angular 中使用 DecimalPipe 對數字進行進位或捨位


如何在 Angular 中使用 DecimalPipe 將數字進位或捨位
我認為,DecimalPipe 預設會對數字進行四捨五入,例如:

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

就我而言,我想將一個數字進位/捨位,例如:

 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

我如何能直接使用 DecimalPipe 達成這個目標?

答案#1

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 遊樂場

用法:

將 {{value | toFixed:2:"up"}} 進位

1.234 => 1.24

1.235 => 1.24

將 {{value | toFixed:2:"down"}} 向下取整

1.234 => 1.23

1.235 => 1.23

答案#2

試試 Decimal JS:

import Decimal from "decimal.js";

let r: Decimal.Rounding = Decimal.ROUND_DOWN;
let c: Decimal.Configuration = {rounding: r };
Decimal.set(c);
let v: Decimal.Value = "12345.6789";
let d: Decimal = new Decimal(v);

document.getElementById("app").innerHTML = `
  <div>
    ${d.toFixed(3)}
  </div>`