- Home /
How to make a float hold only entire numbers
This is a complicated thing to explain on the title, so most people will probaly ignore it, but the question itself is something actually very easy, i just don't have any idea of how to do it lol Anyway, i have a float on a script, and the script makes some math with the float, and then shows the total result on a text so the player can view how many points he has. The problem is that sometimes, the float will be like 1.1,1.2,1.3, etc... I want it to be ALWAYS showing only the entire number. For an example: 1,2,3 etc...
What could i do in my script, that would allow my float to ONLY show entire numbers, and if it is for an example at 4.5, go immediately to 5?
Use this:
$$anonymous$$ath.Round((yourFloat), $$anonymous$$idpointRounding.AwayFromZero)
this will round your float so that: 4.5 to 5; 4.4 to 4
Answer by ObscuredCrow · Mar 12, 2017 at 05:56 AM
Usually if you want to make a float state a whole number only you will make it a int before displaying it. This is done like so.
If you want to round to the nearest int:
int rounded = (int)Math.Round(precise, 0);
You can also use:
int rounded = Convert.ToInt32(precise);
Which will use Math.Round(x, 0); to round and cast for you. It looks neater but is slightly less clear IMO.
If you want to round up:
int roundedUp = (int)Math.Ceiling(precise);
If that doesn't work you might have to try something like this.
int rounded = int.Parse(Math.Round(precise, 0));
Reference: http://stackoverflow.com/questions/904910/how-do-i-round-a-float-up-to-the-nearest-int-in-c
Hope that answers your question, if not let me know and I will see what I can do to help you out.
P.S. It also helps if you put a small snipping of your code for us to look at and give you a more direct response.
Answer by shay4545 · Mar 12, 2017 at 01:57 AM
You could use Mathf.Round() to round the float to the nearest integer
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do I take a public float from a different script and access it 2 Answers
Why do my variables not get changed? 1 Answer
Running a script without being attached to an object? 2 Answers