[英]Is there a way to truncate scientific notation numbers in Javascript?
As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware).众所周知,因为它是关于 SO 的最受关注的话题之一,所以我遇到了舍入错误的问题(这实际上不是错误,我很清楚)。 Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:
我将举例说明我有哪些可能的数字以及我希望能够获得哪些输入,而不是解释我的观点:
Let's say比方说
var a = 15 * 1e-9;
alert(a)
outputs输出
1.5000000000000002e-8
I want to be able to obtain 1.5e-8
instead, but I cannot just multiply by 10e8, round and divide by 10e8 because I don't know if it will be e-8 or e-45 or anything else.我希望能够获得
1.5e-8
,但我不能只乘以 10e8、四舍五入并除以 10e8,因为我不知道它是 e-8 还是 e-45 或其他任何东西。
So basically I want to be able to obtain the 1.5000002
part, apply toFixed(3)
and put back the exponent part.所以基本上我希望能够获得
1.5000002
部分,应用toFixed(3)
并放回指数部分。
I could convert into a string and parse but it just doesn't seem right...我可以转换成字符串并解析,但它似乎不正确......
Any idea?任何想法?
(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones) (如果您觉得这是许多重复项之一,我提前道歉,但我找不到类似的问题,只有相关的问题)
Gael盖尔
You can use the toPrecision
method: 您可以使用
toPrecision
方法:
var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
如果您正在进行科学工作并需要考虑重要数字: 四舍五入到任意数字的有效数字
var a = 15 * 1e-9;变量 a = 15 * 1e-9;
console.log(Number.parseFloat(a).toExponential(2)); console.log(Number.parseFloat(a).toExponential(2));
//the above formula will display the result in the console as: "1.50e-8" //上面的公式将在控制台中显示结果为:“1.50e-8”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.