3 回答

TA貢獻1854條經(jīng)驗 獲得超8個贊
您可以使用以下功能:
var intvalue = Math.floor( floatvalue );
var intvalue = Math.ceil( floatvalue );
var intvalue = Math.round( floatvalue );
// `Math.trunc` was added in ECMAScript 6
var intvalue = Math.trunc( floatvalue );

TA貢獻1877條經(jīng)驗 獲得超1個贊
不是最短但工作
function roundNumberWith05 (num){
const diff = num - Math.floor(num);
if (diff < 0.25 || diff > 0.75) {
return Math.round(num * 2) / 2;
} else {
return num - diff + 0.5;
}
}
console.log('2.1 --', roundNumberWith05(2.1));
console.log('2.4 --', roundNumberWith05(2.4));
console.log('1.9 --', roundNumberWith05(1.9));
console.log('1.75 --', roundNumberWith05(1.75));
console.log('1.74 --', roundNumberWith05(1.74));
console.log('1.76 --', roundNumberWith05(1.76));
console.log('2.688 --', roundNumberWith05(2.688));
console.log('2.2588 --', roundNumberWith05(2.2488));

TA貢獻1893條經(jīng)驗 獲得超10個贊
嘗試這個,
function my_round(x){
return Math.floor(x) + Math.round((x - Math.floor(x)) * 2) / 2
}
或者更好的是,使用@ritaj 建議的方法
function myRound(x){
return Math.round(x * 2)/2
}
添加回答
舉報