Angular 2 - Number pipe for scientific notation numbers

故事扮演 提交于 2019-12-24 10:57:43

问题


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:


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.



来源:https://stackoverflow.com/questions/43859972/angular-2-number-pipe-for-scientific-notation-numbers

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