问题
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