javascript - 寻找更接近的值

标签 javascript html

我想找到一个更接近特定数字的数字。在当前示例中,分数为 15。我将把 n 传递给方法,它将返回最接近的完全除以 15 的值 我想要一个这样的方法

function getCloser(no){
    if(no is closer to 0)    // in this case no can be 1,2,3,4,5,6,7
        return 0
    if(no is closer to 15)   // in this case no can be 8,9,10,11,12,13,15,16...22
        return 15
    if(no is closer to 30)   // in this case no can be 23 to 37
        return 30
    and so on...

}

最佳答案

function getCloser(a, b) {
    b = b || 15;
    return Math.round(a / b) * b;
}

关于javascript - 寻找更接近的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8653362/

相关文章:

javascript - Ajax - 多次调用会减慢我的服务器速度

javascript - 415(不支持的媒体类型)与 REST 发布请求

javascript - 某些时间的空白数据 - 因此在我的数组中丢失。有没有办法填补缺失的时间?

javascript - 使用 id 来连接

javascript - 减少 "firstDuplicate"算法的执行时间

css - 如果内容超出 html div 的固定宽度,如何将文本放入下一行

html - 图像/SVG 改变颜色?

html - Bootstrap 拉柱包装

jquery - 在没有 id 的 div 中查找特定标签

javascript - 如何让下拉选项显示在此待办事项列表条目的左侧?