Truncate/round whole number in JavaScript?

前端 未结 6 1024
长发绾君心
长发绾君心 2020-12-24 00:11

For a script I\'m writing, I need display a number that has been rounded, but not the decimal or anything past it. I\'ve gotten down to rounding it to the third place, but I

6条回答
  •  無奈伤痛
    2020-12-24 00:52

    Travis Pessetto's answer along with mozey's trunc2 function were the only correct answers, considering how JavaScript represents very small or very large floating point numbers in scientific notation.

    For example, parseInt(-2.2043642353916286e-15) will not correctly parse that input. Instead of returning 0 it will return -2.

    This is the correct (and imho the least insane) way to do it:

    function truncate(number)
    {
        return number > 0
             ? Math.floor(number)
             : Math.ceil(number);
    }
    

提交回复
热议问题