本文介绍了Angular 2-科学计数法的数字管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用数字管道(数字:'1.2-2')将小数点四舍五入.它适用于标准格式编号,但对于科学格式编号(指数),结果以标准格式返回.

例如,如果我将上述数字管道应用于1.336274995924138e + 306,我期望1.34e + 306,但我得到的是133627499592414000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

在Angular JS 1.x中同样可以正常工作.

请告知如何以与原始编号相同的符号返回结果.

解决方案

对于num = 1.336274995924138e + 306

  num.toPrecision(3) 

具有3个有效数字的科学计数法...即1.34e + 306

这是一个带有自定义管道的Plunker示例,当数量较大时,该管道将使用 toPrecision ,否则,它将使用您一直在使用的 DecimalPipe .自定义管道示例

如果要将其合并到代码库中,请查看其在主应用程序模块中的引用方式.

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.

解决方案

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.

这篇关于Angular 2-科学计数法的数字管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:51