在JavaScript中将浮点转换为整数的最佳方法是什么?
在JavaScript中,有几种不同的方法可以将浮点数转换为Integers。我的问题是哪种方法可以提供最佳性能,最兼容或者被认为是最佳实践?
我知道以下几种方法:
var a = 2.5; window.parseInt(a); // 2 Math.floor(a); // 2 a | 0; // 2
我确定那里还有其他人。有什么建议吗?
解决方案
parseInt()可能是最好的一种。 a | 0
并没有满足实际需求(如果a是未定义或者null值,则仅分配0,这意味着空对象或者数组通过了测试),而Math.floor则通过某种类型的欺骗手段起作用(它基本上调用parseInt ()在背景中)。
我们可以使用Number(a).toFixed(0);
甚至只是a.toFixed(0);
编辑:
舍入到0位,与截断略有不同,并且正如其他人建议的那样,toFixed返回一个字符串,而不是原始整数。用于显示目的。
var num = 2.7; // typeof num is "Number" num.toFixed(0) == "3"
根据这个网站:
parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number... For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable...
var i = parseInt(n, 10);
如果不指定基数,则将像'010'那样的基数视为八进制(因此结果将是'8'而不是'10')。
问题似乎是在专门询问从浮点数转换为int的问题。我的理解是,做到这一点的方法是使用" toFixed"。所以...
var myFloat = 2.5; var myInt = myFloat.toFixed(0);
有谁知道" Math.floor()"比" Number.toFixed()"具有更高的性能?
答案已经给出,但需要明确。
为此使用数学库。圆形,天花板或者地板功能。
parseInt用于将字符串转换为int,这不是这里所需要的
toFixed用于将浮点数转换为字符串,这里也不需要
由于Math函数不会在字符串之间进行任何转换,因此它将比其他任何错误的选择都快。
我们也可以这样操作:
var string = '1'; var integer = a * 1;
显然,按位加倍不是-是对数字求和的最快方法:
var x = 2.5; console.log(~~x); // 2
曾经是这里的文章,现在却获得了404:http://james.padolsey.com/javascript/double-bitwise-not/
Google已将其缓存:http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.com/javascript/double-bitwise-not/+double+bitwise+not&cd=1&hl=zh-CN&ct=clnk&gl=us
但是Wayback Machine可以节省一天! http://web.archive.org/web/20100422040551/http://james.padolsey.com/javascript/double-bitwise-not/