unity-game-enginetetris

Unity - truncate all decimals from a float (not by rounding)


I have a C# script in which I want to take a float value, remove everything after the decimal point and have an int of the remaining figure.

e.g. 2.5469 would ultimately be [int]2. e.g. 546.5934 should be [int]546.

I am using the int for another calculation, so I cannot just use String formatting. Math.Roundf won't work either, since I don't want it to be rounded.

It's for a tetris clone, I'm trying to create a range of X-axis values where the game pieces are permitted to spawn. I thought a simple way would be to draw the play area in my scene, by defining it with sprites, and pull the transform.position.x value for those sprites to find the range of the area. This is why I don't want to use the float with decimals.

E.g. if my right boundary is at transform.position.x of 10.25, and left is at transform.position.x of -10.6, then I want pieces to be able to spawn at any of: [-8, -7, -6, ..., 0, 1, 2, ... 8]. I think it will be a cleaner experience than having them spawn at any possible float value between -8 and 8.

So to get that range I plan take the 10 and -10 from 10.25 and -10.6, add/subtract 2 (to ensure that when pieces are spawned they don't overlap the edges of the play area), then pull a random int in that range for the x position of the next spawned piece.

Unfortunately, I can't find an easy way to get 10 from 10.25 or -10 from -10.6.

Easiest solution is just to set the boundaries at x 10.0 and x -10.0. However I'd like a solution where the boundaries don't have to be at such specific coordinates, i.e. one that allows for a sprite placed at x of 10.12 and will truncate the decimals from the float value of transform.x.position before calculating further.


Solution

  • You can either use Mathf.FloorToInt or casting to int. If you want to know which is more performant, check this answer.