Rounding up to the nearest 0.05 in JavaScript

前端 未结 7 1965
你的背包
你的背包 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 11:01

    I ended up using this function in my project, successfully:

    roundToNearestFiveCents( number: any ) {
        return parseFloat((Math.round(number / 0.05) * 0.05).toFixed(2));
    }
    

    Might be of use to someone wanting to simply round to the nearest 5 cents on their monetary results, keeps the result a number, so if you perform addition on it further it won't result in string concatenation; also doesn't unnecessarily round up as a few of the other answers pointed out. Also limits it to two decimals, which is customary with finance.

    0 讨论(0)
提交回复
热议问题