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

后端 未结 12 2107
梦如初夏
梦如初夏 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

    You can use Number(a).toFixed(0);

    Or even just a.toFixed(0);

    Edit:

    That's rounding to 0 places, slightly different than truncating, and as someone else suggested, toFixed returns a string, not a raw integer. Useful for display purposes.

    var num = 2.7;  // typeof num is "Number"
    num.toFixed(0) == "3"
    

提交回复
热议问题