如何舍入浮点数?

JavaScript 中是否有一些有用的函数可以帮助将任何浮点数舍入到最近的邻居,无论是整数还是带有 .5 的浮点数?


Input -> Output: 


 - > 2.1 -> 2.0


   > 2.4 -> 2.5


   > 1.9 -> 2


....

javascript


SMILET
浏览 118回答 3
3回答

哔哔one

您可以使用以下功能:var intvalue = Math.floor( floatvalue );var intvalue = Math.ceil( floatvalue ); var intvalue = Math.round( floatvalue );// `Math.trunc` was added in ECMAScript 6var intvalue = Math.trunc( floatvalue );

冉冉说

不是最短但工作function roundNumberWith05 (num){&nbsp; const diff = num - Math.floor(num);&nbsp; if (diff < 0.25 || diff > 0.75) {&nbsp; &nbsp; return Math.round(num * 2) / 2;&nbsp; } else {&nbsp; &nbsp; return num - diff + 0.5;&nbsp; }}console.log('2.1 --', roundNumberWith05(2.1));console.log('2.4 --', roundNumberWith05(2.4));console.log('1.9 --', roundNumberWith05(1.9));&nbsp;console.log('1.75 --', roundNumberWith05(1.75));&nbsp;console.log('1.74 --', roundNumberWith05(1.74));&nbsp;console.log('1.76 --', roundNumberWith05(1.76));&nbsp;console.log('2.688 --', roundNumberWith05(2.688));&nbsp;console.log('2.2588 --', roundNumberWith05(2.2488));&nbsp;

白猪掌柜的

尝试这个,function my_round(x){&nbsp; return Math.floor(x) + Math.round((x - Math.floor(x)) * 2) / 2&nbsp;}或者更好的是,使用@ritaj 建议的方法function myRound(x){&nbsp; return Math.round(x * 2)/2&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript