【问题标题】:Format number to put points on thousands格式化数字以将点放在千位上
【发布时间】:2017-10-24 07:20:41
【问题描述】:

我需要格式化一个数字以将点数以千为单位,我需要使用角度为 2 的管道对其进行格式化。Ejem:数字是 1983839,结果必须是 1.983.839 知道吗?

{{amount | number}}

【问题讨论】:

  • 欢迎尝试使用管道的方法
  • 这将取决于区域设置(在 en-GB 中,我们放置 1,983,839)。 Angular 已经为它提供了一个管道:DecimalPipe.
  • 语言环境是es-ES

标签: angular format pipe


【解决方案1】:

我用这个解决方案解决了这个问题。我使用了提供角度的“DecimalPipe”管道。

我在提供程序的 app.module 中添加了我的语言环境并导入了“LOCALE_ID”:

import { LOCALE_ID } from '@angular/core';

providers: [
  { provide: LOCALE_ID, useValue: "es-ES" },
  ...
]

然后在我的组件中,我使用了 angular 的管道“DecimalPipe”:

component.ts:
   import { DecimalPipe } from '@angular/common';

component.html:
   {{fila.NumeroCopiasBN | Number:'1.0-0' }}

我发送到管道'1.0-0'的参数是一个具有以下格式的字符串:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

【讨论】:

  • 你不应该需要import组件中的管道来在模板中使用它。也是number,全部小写。
  • @jonrsharpe 好的,我删除了组件中的导入管道。 tnx
【解决方案2】:

这里是自定义管道

import { Pipe } from '@angular/core';
import {DecimalPipe} from "@angular/common";

@Pipe({
    name: 'pointReplacer'
})
export class PointReplacerPipe extends DecimalPipe {

  transform(value: any, digits?: string): string {
        return super.transform(value, digits).replace(',', '.');


    }
}

您需要将自定义管道注册到您的模块

@NgModule({
  declarations: [PointReplacerPipe],
  providers: [PointReplacerPipe]
})

【讨论】:

  • 为什么你认为这需要一个自定义管道?千位分隔符只是语言环境配置的一部分。
  • 我解决了它在de管道的构造函数中添加本地到super,这样我就避免了替换。在de pipe的构造函数中:constructor() { super("es-ES"); }
  • 为什么需要在我的模块提供者中注册我的自定义管道?
  • @ararb78 但同样,如果您所做的只是将语言环境传递给父级,您不需要自定义管道。该数字将自动格式化以匹配用户的区域设置。而且您不需要将其注册为提供者,除非您打算将其注入某个地方。
  • @jonrsharpe 是的,我不需要自定义管道,因为在提供程序“{提供:LOCALE_ID,useValue:“es-ES”}”中包含 app.module 的语言环境并设置 {{fila.数据 | Number:'1.0-0' }} 有效。
【解决方案3】:

在你的组件下面提到的代码:

export class appComponent{
    num:number = 1983839;
    printNum:any;
    constructor() {
    this.test = this.num.toLocaleString('es-CO');
    console.log('printNum',this.printNum);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2017-08-23
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多