What is the best method to convert floating point to an integer in JavaScript?

后端 未结 12 2133
梦如初夏
梦如初夏 2020-12-08 05:00

There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatibl

12条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 05:28

    Apparently double bitwise-not is the fastest way to floor a number:

    var x = 2.5;
    console.log(~~x); // 2
    

    Used to be an article here, getting a 404 now though: http://james.padolsey.com/javascript/double-bitwise-not/

    Google has it cached: http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.com/javascript/double-bitwise-not/+double+bitwise+not&cd=1&hl=en&ct=clnk&gl=us

    But the Wayback Machine saves the day! http://web.archive.org/web/20100422040551/http://james.padolsey.com/javascript/double-bitwise-not/

提交回复
热议问题