Rounding up to the nearest 0.05 in JavaScript

前端 未结 7 1973
你的背包
你的背包 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:55

    My solution and test:

    let round = function(number, precision = 2, rounding = 0.05) {
      let multiply = 1 / rounding;
    
      return parseFloat((Math.round(number * multiply) / multiply)).toFixed(precision);
    };
    

    https://jsfiddle.net/maciejSzewczyk/7r1tvhdk/40/

提交回复
热议问题