Skip to content
Advertisement

How to round numbers to the closest .45 or .95?

In PHP I want to round numbers based on the value provided.

  • If the value is more than 30, I want to round numbers to the closest 4.95 or 9.95
  • If the value is between 10 and 30 I want to round numbers to the closest 2.45 or 4.95 or 7.45 or 9.95
  • If the value is less than 10 I want to round numbers to the closest .45 or .95
  • If the value is less than 1 I want to round numbers to the closest .05 or .10

The value however cannot be 0 or below zero and always round upwards when it’s close to zero (so it doesn’t become zero but 0.05 for example).

I have this code for rounding to the closest 4.95 or 9.95:

JavaScript

I have this code for rounding to the closest .45 or .95:

JavaScript

I don’t really know how to achieve the above though. Does anyone have an idea about it?

Advertisement

Answer

If I understand well your problem, this solution should work :

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement