如何在Angular组件中使用DecimalPipe?

22

我有一个需求,需要使用ts中的decimal pipe来转换数字。

与其像这样使用decimal pipe:

<td>{{rmanFmvRulesDef.max  | number :'1.2-2'}}</td>

我希望能够从组件中进行操作,请有人可以帮忙吗?

3个回答

63

和通常在Angular中一样,您可以依靠DI。您可以在ts中覆盖转换函数。

import { DecimalPipe } from '@angular/common';

class MyService {
  constructor(private _decimalPipe: DecimalPipe) {}

  transformDecimal(num) {
    return this._decimalPipe.transform(num, '1.2-2');
  }
}

在providers数组中添加DecimalPipe,否则会出现错误。

providers: [DecimalPipe,...]

1
将管道添加到提供者而不是声明中是一个缺少的导入信息。感谢您! - liqSTAR
正确的格式为“1.2-2”,以供将来参考。 - Ana Franco
1
注意:这与常规管道(显示)的行为不完全相同。在 Angular 9 上观察到。-- 常规格式:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits},而在输入字段或直接 API 中使用的格式为:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits|maxIntegerDigits} - ddsultan
@ddsultan 我也遇到了同样的问题。这个并不像普通的管道显示那样工作。但我不确定你是否有任何解决方案。我尝试过将其设置为“1.2-2 | 1”,但它并没有起作用。 - Goli
@Goli,我使用了自定义的正则表达式。 - ddsultan

6
你还可以使用formatNumber函数(DecimalPipe在内部使用它)。无需处理DI或将任何内容添加到提供程序数组中。

4

或者,您可以在 Stackblitz 上查看示例,使用 accounting

只需简单调用:element.price = format.formatCurrency(element.price);

定义助手后,您可以按如下方式进行定义: <h2 *ngFor="let item of item">{{ item.price }}</h2> 作为示例。

组件:

import { accounting } from 'accounting';

export function formatCurrency(value) {
    return accounting.formatMoney(value, '', 0, ' ', '.');
}

export function unformatCurrency(value) {
    return accounting.unformat(value);
}

注意:return accounting.formatMoney(value, '', 0, ' ', '.'); 你可以用任何分隔符替换' '.,比如,或空格。如果要更新小数点后的位数,则可以将0更改为所需的位数。

什么是会计? - Bogdan
https://github.com/openexchangerates/accounting.js - Mukyuu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接