【问题标题】:separators of thousands in angular 2角度 2 中的千位分隔符
【发布时间】:2017-08-24 23:00:37
【问题描述】:

我已经在我的项目中尝试过这个:

<div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | number }}  
</div>

我的变量名为TotalAPagar,我使用的是数字管道,但它显示的值类似于1,000,500

我需要将编号约定更改为dots。例如。 1.000.000

我一直在阅读有关角度的文档,但没有任何示例。

【问题讨论】:

  • 你不应该这样做,因为十进制数字使用点来标记分数。
  • 您看过currency 管道吗?可以通过 LOCALE_ID 提供程序处理特定于语言环境的方面。如果您想要动态语言环境,您可以考虑自定义/子类化货币管道。
  • @coderek 有一个叫做“德国”的国家,1.234.567,12€ 将是一百万二十三万五百六十七欧元和 12 美分,所以....:D

标签: angular typescript ionic2


【解决方案1】:

我认为有两种方法可以解决这个问题:


1.您可以尝试从 @angular/common 库中覆盖 DecimalPipe:

这样:

point-replacer.pipe.ts

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(',', '.');


    }
}

在您的 html 代码中:

<div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | pointReplacer }}  
</div>

2。您可以编写自己的管道,替换字符并在您的 html 代码中使用**双管道**

这样试试:

point-replacer.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'pointReplacer'
})

export class PointReplacerPipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if(value) {
          return value.replace(',', '.');
        }
        return '';
    }
}

在您的 html 代码中:

<div padding *ngIf="TotalAPagar">
    $ {{TotalAPagar | number | pointReplacer }}  
</div>

无论你选择哪种方法,不要忘记在你使用它的模块中声明你自己的管道:

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

【讨论】:

  • 这不是一个可靠的解决方案。您将如何使其适应印度号码分组,例如1,00,000?数字和货币应使用数字和货币格式化库进行格式化,而不是通过临时字符串操作。
【解决方案2】:

​在阅读有关 angular js y javascript 的论坛和文档后,我发现了一种将数字置于格式和货币中的方法,该方法是 toLocaleString(),是一种来自 javascript 的方法,有助于将其放入货币或语言中你需要的。

我使用该方法搜索我需要的国家/地区的名称,并向我显示需要的信息。 (http://www.localeplanet.com/icu/es-CO/),在我的例子中是哥伦比亚。

在我的函数中,我只需将 .toLocaleString('es-CO') 添加到结果中,然后使用指定的货币输入值。

例如:

this.TotalAPagar = (this.calcularDescuentosLiquidacion(this.TotalDevengadoValor, this.sueldoPendientePorCancelarValor, this.item.libranza, this.item.prestamo_empleado)+ this.calcularIndemnizacion(this.item.promedio_salario, this.item.fecha_fin_contrato, this.item.fecha_inicio_contrato)).toLocaleString('es-CO');

【讨论】:

    【解决方案3】:

    我认为这是一个更清洁的解决方案:

    在 app.modules.ts 中导入 LOCALE_ID

    import {ErrorHandler, NgModule, LOCALE_ID} from '@angular/core';
    

    并像这样在提供者中定义:

      providers: [
        PouchServiceProvider,
        DbProvider, {
          provide: LOCALE_ID,
          useValue: "nl-NL"
        }
      ]
    

    这将根据 local_id 自动选择分隔符 id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 2011-12-10
      • 2011-12-06
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多