Angular 2 - Number pipe for scientific notation nu

2019-08-02 03:58发布

I'm using number pipe (number:'1.2-2') to round off the decimals. It works fine for standard format numbers but for scientific format numbers (exponential) the result is returned in standard format.

For example if I apply the above number pipe to 1.336274995924138e+306 I expect 1.34e+306 but what I get is 1336274995924140000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.

The same works fine in Angular JS 1.x.

Please advise how can I get back result in the same notation as the original number.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-02 04:50

For num = 1.336274995924138e+306

num.toPrecision(3)

results in scientific notation with 3 significant figures...i.e. 1.34e+306

Here's a Plunker example with a custom pipe that will use toPrecision when the number is large, otherwise, it'll use the DecimalPipe that you've been using. Custom Pipe Example

If you want to incorporate this in you codebase, check out how its referenced in the main app module.

查看更多
登录 后发表回答