如何使用角度中的DecimalPipe向上或向下舍入数字

时间:2017-08-07 06:24:49

标签: 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直接实现此目的?

2 个答案:

答案 0 :(得分:1)

如果有人想在html中进行操作而不必创建管道。

在您的app.component.ts

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>rund up value {{ (math.ceil(value * 100) / 100).toFixed(2) }}</h2>
      <h2>rund down value {{ value.toFixed(2) }}</h2>
      <h2>rund value {{ (math.round(value* 100) / 100).toFixed(2) }}</h2>
    </div>
  `,
})
export class App {
  math = Math;
}

toFixed()函数中给出的数字定义了您希望进行此回合的深度

例如,如果要四舍五入到小数点后第四位

 Math.round(value * 10000)/10000).toFixed(4)

where I found the Idea,它也在解释它是如何逐步工作的。

答案 1 :(得分:0)

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

用法:

四舍五入 {{value | toFixed:2:"up"}}

1.234 => 1.24

1.235 => 1.24

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

1.234 => 1.23

1.235 => 1.23