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

后端 未结 4 1586
广开言路
广开言路 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

    Divide the number by 0.25 (or whatever fraction you want to round nearest to).

    Round up to nearest whole number.

    Multiply result by 0.25.

    Math.ceil(1.0005 / 0.25) * 0.25
    // 1.25
    
    Math.ceil(1.9 / 0.25) * 0.25
    // 2
    
    // etc.
    

    function toNearest(num, frac) {
      return Math.ceil(num / frac) * frac;
    }
    
    var o = document.getElementById("output");
    
    o.innerHTML += "1.0005 => " + toNearest(1.0005, 0.25) + "
    "; o.innerHTML += "1.9 => " + toNearest(1.9, 0.25) + "
    "; o.innerHTML += "2.10 => " + toNearest(2.10, 0.25) + "
    "; o.innerHTML += "2.59 => " + toNearest(2.59, 0.25);

提交回复
热议问题