如何在javascript中找到最接近的最高千位

问题描述 投票:0回答:3

我需要从整数中找到最接近的最高1000

例如

let Num = 110;  //result will be 1000 
let num2 = 1280 // result will be 2000 

我尝试过以下示例,但它也给出了最低值

var round = Math.round(Num) // I am getting 100 only 
javascript jquery
3个回答
2
投票

除以你想要舍入的十位,然后乘以该数。使用Math.ceil所以它总是向上舍入:

let num1 = 110
let num2 = 1280
let num3 = -110

console.log( nearestThousand(num1) )  // 1000
console.log( nearestThousand(num2) )  // 2000
console.log( nearestThousand(num3) )  // 0 <-- determine expected behavior

function nearestThousand(n){
  return Math.ceil(n/1000)*1000
}

1
投票

你可以试试这个:

var result = Math.round(val/1000)*1000 == 0 ? 1000 : Math.round(val/1000)*1000;

如果你想要舍入到下一个千分之一的值,请使用它

var result = Math.round(val/1000)*1000 + 1000;

0
投票
function nearestHighestThousand(value) {
    if (value < 1) {
        return 1000;
    } else if (value > 9000) {
        return 9000;
    } else {
        return Math.ceil(value / 1000) * 1000;
    }
}

var round = nearestHighestThousand(num);
© www.soinside.com 2019 - 2024. All rights reserved.