[removed] rounding a float UP to nearest .25 (or whatever…)

后端 未结 4 1581
广开言路
广开言路 2021-01-21 03:39

All answers I can find are rounding to nearest, not up to the value... for example

1.0005 => 1.25  (not 1.00)
1.9   => 2.00
2.10 => 2.25
2.59 => 2.75         


        
4条回答
  •  没有蜡笔的小新
    2021-01-21 04:23

    Other divide and multiply will not work for some values such as 1.59 You can try customRound function

    function customRound(x) {
        var rest = x - Math.floor(x)
    
        if (rest >= 0.875) {
            return Math.floor(x) + 1
        } else if (rest >= 0.625) {
            return Math.floor(x) + 0.75
        } else if (rest >= 0.375) {
            return Math.floor(x) + 0.50
        }  else if (rest >= 0.125){
            return Math.floor(x) + 0.25
        } else {
            return Math.floor(x)
        }
    }
    

提交回复
热议问题