This site uses strictly necessary cookies. More Information

X- Home /

# % Modulo with float, and Mathf.PI

Hi I am scratching my head :

120%60= 0 //OK

49.5%5.5=0 //OK

4.71%1.57=1.57 // how is is possible?

(3*(global::UnityEngine.Mathf.PI/2))%(global::UnityEngine.Mathf.PI/2)= 1.570796 ?

471%157 = 0

It's quite strange, it seems to link with the variable type.

I need to make this opération :

float d = X -X % (Mathf.PI / 2);

Where X is between 0 and 2Mathf.PI , but the result is not the one expected when X = 3PI/2 Thanks for your help

**Answer** by Bunny83
·
Nov 21, 2020 at 12:43 PM

This should answer all your questions. To explain your exact usecase:

The number 3 * Pi/2 is of course larger than PI/2. That means 3*PI/2 has roughly one digit less behind the "binary point" and the number is probably slightly smaller than your divisor. So the modulo will just return that remainder which is slightly smaller than the divisor you're using. It's even possible that after the modulo operation that the result is rounded to the same number as your divisor since the number is not smaller than the original number and you have one digit more behind the binary point.

Over here I've posted a table to get a better intuition how many (binary) digits you have before / after the binary point depending on the floating range of a number.

ps: Since you want to calculate

```
float d = X -X % ($$anonymous$$athf.PI / 2);
```

That should be simply rounding (or Flooring) the number properly. Namely

```
float d = $$anonymous$$athf.Floor(X * 2f / $$anonymous$$athf.PI) * $$anonymous$$athf.PI*0.5f;
```

Though when it comes to directions you often want to round instead of flooring. Though that's up to your usecase.

Thanks, it was exactly that ! I have seen with number than changing from double to float works, but Your answer definitely do the job! Thanks a lot again

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.

### Follow this Question

### Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How do I programmatically specify direction from a given vector? 1 Answer

Flip over an object (smooth transition) 3 Answers

problem after rotate an object 0 Answers