Beni
Beni

Reputation: 149

Double divided by 1

I guess this is more of a math question, but how come when you divide a double by 1 it returns the decimal points too?

For example, 123.23 % 1 is equal to 0.23.

Shouldn't it return only 0?

MSDN reference says that module does this ex - (x / y) * y where x is the dividend and why is the divider and if you calculate it like that it should return 0.

So tell me how come does it return the decimal points too?

Upvotes: 1

Views: 229

Answers (1)

Jens
Jens

Reputation: 6375

You are not simply dividing by 1, you are taking the modulus. The modulus returns the remainder from the division of the first argument with the second.

This means it subtracts the highest complete divider from the input and returns the remainder. In your case that would be

123.23 - 123 = 0.23

since 123 can be divided by 1 without "anything left". What's left is then the 0.23 you experience.

The modulus operator is handy in many situations. Two very common ones are:

Checking for Even/Odd numbers
If you have an integer number and take the modulo 2 the result is 1 for odd and 0 for even numbers.

Checking for the nth iteration
If you have a loop and say you want to print a result every 10th iteration you could have a continous counter and use code like

if (Counter % 10 == 0) then { 
    Console.WriteLine("Tick Tock"); 
}

See MSDN for further examples: https://msdn.microsoft.com/de-de/library/0w4e0fzs.aspx?f=255&MSPPError=-2147217396

Upvotes: 5

Related Questions