3 回答
TA贡献1854条经验 获得超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条经验 获得超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条经验 获得超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
}
添加回答
举报