【问题标题】:Number pipes in Angular2 not working as I would expectAngular2 中的数字管道没有像我预期的那样工作
【发布时间】:2016-06-06 08:59:12
【问题描述】:
platform-browser.umd.js:962 ORIGINAL EXCEPTION: 2 is not a valid digit info for number pipes

这是我在我的模板中写这个得到的:

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

我的意图是产生一个只有两位小数的十进制数。有人可以指出我做错了什么吗?这是文档:https://docs.angularjs.org/api/ng/filter/number

【问题讨论】:

  • |number:'2' 呢?
  • 我可以试试。当说话的数字必须带一个字符串(lol)
  • 这个参数是一个字符串,它需要匹配github.com/angular/angular/blob/… ({minIntegerDigits}.{minFractionDigits}-{maxFractionDigits})
  • 对不起,它似乎没有任何区别。我无法直接检查模板,因为它已在构建过程中转换。但我会尝试检查组件中的 TypeScript。

标签: angular numbers


【解决方案1】:

您可能正在寻找DecimalPipe

格式作为参数传递给管道,如下所示:

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

根据您的需要使用它:

number:'1.2-2'

这将为您提供一个小数点前最少 1 位,小数点后正好 2 位的字符串。


文档中的示例用法:

@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;
}

【讨论】:

    【解决方案2】:
    {{ tradePrice }}             // output 2345.78543566   
    {{ tradePrice | number : '.1-3' }}   // output 2345.785
    

    这些值来自 API。 Java中的等价物

    tradePrice.toFixed(3)  // output 2345.785
    

    【讨论】:

      猜你喜欢
      • 2016-06-19
      • 2013-04-11
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 2022-12-29
      • 2023-01-01
      相关资源
      最近更新 更多