Rounding up to the nearest 0.05 in JavaScript

前端 未结 7 1966
你的背包
你的背包 2020-12-17 10:19

Question
Does anyone know of a way to round a float to the nearest 0.05 in JavaScript?

Example

BEFORE | AFTER         


        
7条回答
  •  北海茫月
    2020-12-17 10:57

    I would write a function that does it for you by

    • move the decimal over two places (multiply by 100)
    • then mod (%) that inflatedNumber by 5 and get the remainder
    • subtract the remainder from 5 so that you know what the 'gap'(ceilGap) is between your number and the next closest .05
    • finally, divide your inflatedNumber by 100 so that it goes back to your original float, and voila, your num will be rounded up to the nearest .05.

      function calcNearestPointZeroFive(num){
          var inflatedNumber = num*100,
              remainder     = inflatedNumber % 5;
              ceilGap       = 5 - remainder
      
          return (inflatedNumber + ceilGap)/100
      }
      

    If you want to leave numbers like 5.50 untouched you can always add this checker:

    if (remainder===0){
        return num
    } else {
        var ceilGap  = 5 - remainder
        return (inflatedNumber + ceilGap)/100
    }
    

提交回复
热议问题