以角4显示百万或千格式的数字 [英] Display number in Million or Thousand format in angular 4

查看:85
本文介绍了以角4显示百万或千格式的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的angular 4应用程序中显示数字格式.基本上我在看的是如果该数字是1223万,那么它应该显示为例如 12.2M(小数点后一位)

I am trying to display number format in my angular 4 application. Basically what i am looking at is if the number is in 12.23 millions then it should display For e.g 12.2M (One decimal place)

如果数字为50,000.123,则为50.1K

If the number is 50,000.123 then 50.1K

我如何才能做到这一点.我需要写指令吗?角铁中有内置管道吗?

How do i achieve that in angular. Do I need to write a directive ? Are there any inbuilt pipes in angular ?

结构

export interface NpvResults  {

            captiveInsYear: number[];
            captiveInsPremiumPaid: number[];
            captiveInsTaxDeduction: number[];
            captiveInsLoanToParent: number[];
            captiveInsCapitalContribution: number[];
            captiveDividentDistribution: number[];
            captiveInsTerminalValue: number[];

        }

该数组初始化为以下值

this.sourceResults.captiveInsPremiumPaid = [1,2,3,4,5];

html

<td *ngFor= "let item of NpvResults.captiveInsPremiumPaid" >{{item}}</td>

推荐答案

您可以创建 PIPE

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

@Pipe({
  name: 'thousandSuff'
})
export class ThousandSuffixesPipe implements PipeTransform {

  transform(input: any, args?: any): any {
    var exp, rounded,
      suffixes = ['k', 'M', 'G', 'T', 'P', 'E'];

    if (Number.isNaN(input)) {
      return null;
    }

    if (input < 1000) {
      return input;
    }

    exp = Math.floor(Math.log(input) / Math.log(1000));

    return (input / Math.pow(1000, exp)).toFixed(args) + suffixes[exp - 1];


  }

}

视图中的实现

{{ model | thousandSuff  }} <!-- 0 decimals -->

{{ model | thousandSuff : 2  }}  <!-- X decimals -->

结果

{{22600000 | illionSuff}}-> 23M

{{ 22600000 | thousandSuff }} -> 23M

{{22600000 | monthSuff:2}}-> 22.60M

{{ 22600000 | thousandSuff : 2 }} -> 22.60M

这篇关于以角4显示百万或千格式的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆