Round a decimal number using Modulo operator

If you ever need to round a number, you can easily do that by using a Modulo operator. Modulo operator returns a remainder after division of one number with another. So, if we do a modulo operation of some decimal number with a number 1, we will get a remainder after the decimal point (dot which separates the whole number from the fractional part of that number).

For example, let’s say that we want to round a number 3.5 to 3.

In Java, we can do it like this:

int roundedNumber = (int) (3.5 - (3.5 % 1));

So, we subtract the remainder ( 0.5 ) from number 3.5, and then we cast it to integer. We need to cast it since Java is a strongly typed language.

In PHP, we can do it like this:

$roundedNumber = 3.5 - fmod( 3.5, 1 );

Notice that in PHP we need to use a fmod() function. In PHP there is a Modulo ( % ) operator, but in only works with integers. Function fmod() also deals with decimal numbers.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: