Truncate/round whole number in JavaScript?

前端 未结 6 1026
长发绾君心
长发绾君心 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 01:10

    If you have a string, parse it as an integer:

    var num = '20.536';
    var result = parseInt(num, 10);  // 20
    

    If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

    var num = -2147483649.536;
    var result = Math.trunc(num);  // -2147483649
    

    If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

    var num = 20.536;
    var result = Math.floor(num);  // 20
    

    And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

    var num = -20.536;
    var result = num | 0;  // -20
    

提交回复
热议问题