Number pipes in Angular2 not working as I would expect

橙三吉。 提交于 2019-12-06 17:11:55

问题


platform-browser.umd.js:962 ORIGINAL EXCEPTION: 2 is not a valid digit info for number pipes

Is what I get from writing this in my template:

<li>Percentage satisfied: {{selectedCountry.averageSatisfaction | number:2}}</li>

My intention is to produce a decimal number with only two decimals. Can someone please point out what I am doing wrong? Here is the documentation: https://docs.angularjs.org/api/ng/filter/number


回答1:


You're probably looking for the DecimalPipe.

The formatting is passed as a parameter to the pipe like this:

number:'{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}'

Using this with your needs:

number:'1.2-2'

This will give you a string with minimum 1 digit before decimal point and exactly 2 after decimal point.


Example usage from the docs:

@Component({
  selector: 'number-example',
  pipes: [DecimalPipe],
  template: `<div>
    <p>e (no formatting): {{e}}</p>
    <p>e (3.1-5): {{e | number:'3.1-5'}}</p>
    <p>pi (no formatting): {{pi}}</p>
    <p>pi (3.5-5): {{pi | number:'3.5-5'}}</p>
  </div>`
})
export class NumberPipeExample {
  pi: number = 3.141;
  e: number = 2.718281828459045;
}


来源:https://stackoverflow.com/questions/37653308/number-pipes-in-angular2-not-working-as-i-would-expect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!