Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up to the nearest 0.05 in JavaScript

Tags:

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

Example

BEFORE | AFTER
  2.51 | 2.55
  2.50 | 2.50
  2.56 | 2.60

Current Code

var _ceil = Math.ceil;
Math.ceil = function(number, decimals){
    if (arguments.length == 1)
    return _ceil(number);

    multiplier = Math.pow(10, decimals);
    return _ceil(number * multiplier) / multiplier;
}

Then elsewhere... return (Math.ceil((amount - 0.05), 1) + 0.05).toFixed(2);

Which is resulting in...

BEFORE | AFTER
  2.51 | 2.55
  2.50 | 2.55
  2.56 | 2.65
like image 974
Sam Avatar asked May 02 '12 12:05

Sam


People also ask

How do I round to 0.5 in JavaScript?

roundHalf(0.6) => returns 0.5. roundHalf(15.27) => returns 15.5.

What is 0.5 rounded up?

Why is 0.5 rounded up? It is exactly halfway between 0 and 1, so it is not closer to 1... nor is it closer to 0. It is exactly halfway between them.

How do you round a decimal number in JavaScript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).


1 Answers

Multiply by 20, then divide by 20:

(Math.ceil(number*20)/20).toFixed(2)
like image 90
Rob W Avatar answered Sep 30 '22 15:09

Rob W