如果它小于任何0.5的数字,我试图在JavaScript中围绕我的数字。对于Instance,如果我有值3.4那么它应该是3但是如果是3.5则不需要舍入数字。如果小于0.5,我只想舍入数字。这是我用于圆形图的代码。但它在两种情况下均为圆形
此代码为我提供了结果3.5
function rounded(){
var val = 3.5;
var rounded = Math.round(val);
console.log("rounded",rounded);
}
这段代码给了我结果4但我想要3.5 ..
function rounded(){
var val = 3.6;
var rounded = Math.round(val);
console.log("rounded",rounded);
}
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:3)
使用Math.floor向下舍入。
var round = function (num) {
return Math.floor(num * 2) / 2;
};
console.log(round(3)); // 3
console.log(round(3.4)); // 3
console.log(round(3.5)); // 3.5
console.log(round(3.6)); // 3.5
console.log(round(4)); // 4
答案 1 :(得分:0)
这应该截断到最近的.5:
parseInt(x * 2) / 2;