【问题标题】:how to format Angular number pipe output如何格式化角数管道输出
【发布时间】:2016-11-29 09:21:57
【问题描述】:

我正在使用角数管道将四舍五入为 2 位数字 [输入 |number: '1.2-2'],但角数管道以逗号格式给出结果。 输入:1439.333, 输出:1,439.33, 预期输出:1439.33。 有没有办法做到这一点。我在 Angular 2 上,不想使用 javascript。 谢谢,

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以制作自己的管道:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({name: 'numberFormat'})
    export class NumberFormatPipe implements PipeTransform {
     transform(value: number): number {
        return ...;
      }
    }
    

    【讨论】:

    【解决方案2】:

    最好的办法是使用自定义管道并在使用数字管道后将其添加到 html:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({name: 'commadumper'})
    
    export class NumberFormatPipe implements PipeTransform {
        transform(value: number): number {
            if (!value) {
               return '';
            }
            return value.replace(',', '');
        }
    }
    

    然后在你的html中你可以这样使用它:

    [input |number: '1.2-2' | commadumper]
    

    顺便说一句:在做任何事情之前,我建议检查您的系统编号格式(我的意思是客户端),因为它可能是添加逗号。

    【讨论】:

      【解决方案3】:

      在这里查看:https://angular.io/docs/ts/latest/api/common/index/DecimalPipe-pipe.html

      警告:此管道使用国际化 API,该 API 尚未在所有浏览器中可用,并且可能需要 polyfill。有关详细信息,请参阅浏览器支持。

      编辑: 您还可以通过在 app.module.ts 中添加类似的内容来强制使用 Angular 管道使用的语言环境:

      providers: [
        { provide: LOCALE_ID, useValue: "en-US" }, //try some locale here
        appRoutingProviders,
        ...
      ]`
      

      【讨论】:

      • 我只用过这个,输出时用逗号。
      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      相关资源
      最近更新 更多