Rounding up to the nearest 0.05 in JavaScript

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

    I would go for the standard of actually dividing by the number you're factoring it to, and rounding that and multiplying it back again after. That seems to be a proper working method which you can use with any number and maintain the mental image of what you are trying to achieve.

    var val = 26.14,
        factor = 0.05;
    
    val = Math.round(val / factor) * factor;
    

    This will work for tens, hundreds or any number. If you are specifically rounding to the higher number then use Math.ceil instead of Math.round.

    Another method specifically for rounding just to 1 or more decimal places (rather than half a place) is the following:

    Number(Number(1.5454545).toFixed(1));
    

    It creates a fixed number string and then turns it into a real Number.

提交回复
热议问题