console.log(0.1 + 0.2)
// 输出为: 0.30000000000000004
在我们正常的数学思维逻辑来说, 上面会返回 0.3; 但是由于 javaScript 中的数字按照 IEEE 754 的标准,使用 64 位双精度浮点型来表示, 会产生精度问题,具体原因参见这里。 这篇文章主要介绍我们项目怎么解决这些问题。
在 angular 项目中, angular 有自己的解决办法 — DecimalPipe 和 FormatNumber。
DecimalPipe - number
在模板中将数字格式化, 使用格式为:
{{ value_expression | number : digitsInfo : locale }}
number 为数字个格式化 pipe, digitsInfo 和 locale 都为 pipe 的参数; 默认值都为 undefined;
digitsInfo 的格式为:
{最少整数位数}.{最少小数位数}-{{最多小数位数}
-
其中 最少整数位数 默认为 1
-
最少小数位数 默认为 0
-
最多小数位数 默认为 3
-
当小数位数 少于规定的 {最少小数位数} 时,会自动补 0
-
当小数位数 多于规定的 {最多小数位数} 时,会四舍五入
如:
<p>{{ 23456.789| number:'0.2-2' }}</p>
<!-- 23456.79 -->
<p> {{ 678 | number: '0.2-2'}}</p>
<!-- 678.00 -->
<p> {{ 0.004 | number: '0.4-4'}}</p>
<!-- 0.0040 -->
<p> {{ 0.004 | number: '2.4-4'}}</p>
<!-- 00.0040 -->
FormatNumber(value: number, locale: string,digitsInfo?: string:): string;
用于在 ts 中处理数字;
-
value:要格式化的数字;
-
locale:用于标识某个区域的本地环境;
-
digitsInfo: 十进制表示形式的选项, 和 DecimalPipe 中 digitsInfo 一样;
如:
import { formatNumber } from '@angular/common';
import { Inject, LOCALE_ID } from '@angular/core';
export class DemoComponent {
constructor(
@Inject(LOCALE_ID) private localeId: string,
) {
console.log(formatNumber(23.3456, this.localeId, '1.1-3'));
// 23.345
console.log(formatNumber(23.3456, this.localeId, '1.5-6'));
// 23.34560
}
}