繁体   English   中英

我应该使用`.toPrecision()`而不是四舍五入和取幂吗?

[英]Should I use `.toPrecision()` instead of rounding & exponentiation?

我的意思是,

我应该使用这个干净的代码...

var rounded=num.toFixed(n);

...而不是这个丑陋的代码...

var pow10=Math.pow(10,n),
    rounded=''+Math.round(num*pow10)/pow10;

即使第二个要快得多? http://jsperf.com/round-numbers-number-decimals/2

为什么第一个这么慢? 浏览器无法为第一个实现第二个代码吗?

除非您有一个特殊的用例,需要大量的迭代速度,否则我会坚持使用.toFixed()因为它很容易阅读和理解您在做什么。 但是,如果您必须优化速度,至少您知道可以从哪里开始!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM