Floating point numbers are not exact!

1.05 can as well be 1.049999999 or 1.050000001 (or similar).

In this exact case e.g. 1.0499999523162841796875.

Instead of casting (int) which always simply cuts of the decimals simply use Mathf.RoundToInt which would result in 105 as well without the need for heavier data types (like double or decimal)

Answer from derHugo on Stack Overflow
🌐
Reddit
reddit.com › r/unity3d › convert float to int
r/Unity3D on Reddit: Convert float to int
August 13, 2017 -

Hi everyone.

Im struggling to convert a float to an int and ive done reading up but cant seem to figure out what im doing wrong. I want health to be converted it the health display int so i cant dispaly it as a string.

here is my code

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;

namespace Daniel { public class Living : MonoBehaviour, IDamagable { public float startingHealth; [SerializeField] protected float health; protected bool dead; [SerializeField] int healthDispaly;

    public event System.Action OnDeath;

    public virtual void Start()
    {
        health = startingHealth;
    }

    public void Update()
    {
        healthDispaly = (int)health;
    }

    public void TakeHit(float dmg, RaycastHit hit)
    {
        TakeDamage(dmg);
    }

    public void TakeDamage(float dmg)
    {

        health -= dmg;

        if (health <= 0 && !dead)
        {
            Die();
        }
    }

    public void Die()
    {
        dead = true;
        if(OnDeath != null)
        {
            OnDeath();
        }
        GameObject.Destroy(gameObject);

        if (gameObject.tag == ("Player"))
        {
            SceneManager.LoadScene("mapblocked");
        }
    }
}

}

EDIT :: Solved it. I was using the wrong float value, not my actual health value.

Top answer
1 of 4
6
tbh your code is very confusing. I am unable to figure out what you mean. converting from a float to an int is as simple as casting it int myInt = (int)someFloat; with some of the advanced options like Mathf.RoundToInt() when you want more control over the direction of rounding. whatever your problem is it is most likely not a casting issue. On a design note. why store health as an int and damage as a float if they are designed to interact? use one type for both to make calculations easier then round it for use in UI and displays. The most likely cause for your issues is that they value you think you have is not the value you have. log out the value of the health and see what is happening. if needed attach your editor to unity and step through each line of the code to see what it is doing, EDIT ok, i get it now. that IS what you are doing. I still don't see how casting would be an issue but you should not be doing a calculation like a casting every time in update for no reason. Instead of health -= damage I recommend: private float Health { get{ return health; } set { health = value; UpdateHealthUI(); } } private void UpdateHealthUI(){ int roundedHealth = (int)Health; healthDisplay = roundedHealth; } now in the rest of your code use Health -= damage and forget the lowercase health exists. (in fact i prefer to name it _health to mark is as internal use only)
2 of 4
2
Here: https://docs.unity3d.com/ScriptReference/Mathf.html There's Mathf.RoundToInt() if for rounding to the closest int. Mathf.CeilToInt() to round up. Mathf.FloorToInt() to round down.
🌐
Unity
discussions.unity.com › ui
Converting float to integer - UI - Unity Discussions
July 30, 2009 - how can i convert a float value to integer to display in gui.label. using cs. C#
Discussions

C# float to int conversion problem (in Unity) - Stack Overflow
i'm having a little problem converting float to int in C# (Unity) some how when i try x * 1.05, it comes out x * 1 x * 1.1, it comes out x * 1.05 using System; public class Example { public st... More on stackoverflow.com
🌐 stackoverflow.com
Possible to convert a Float into an Int? - Questions & Answers - Unity Discussions
Hello, I have a value that is being passed onto another script in a float format. I want to place this value as a GUI text, but as its in a float, I get a load of ugly numbers after a decimal. How can I convert this into an Int (or a solid number). I dont want to change the value variable from ... More on discussions.unity.com
🌐 discussions.unity.com
0
April 7, 2011
Converting float to integer - UI - Unity Discussions
how can i convert a float value to integer to display in gui.label. using cs. C# More on forum.unity.com
🌐 forum.unity.com
1
August 30, 2009
c# - How can I convert float to int? - Stack Overflow
This is simply false. Convert.ToInt32 is simply a less efficient way of converting a float to an int. The purpose of Convert.* is for converting a value where you do not know it's type, but know that it's IConvertible, and that's simply not the case here. Using the cast operator is converting ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Unity
discussions.unity.com › scripting
Convert FLOAT to INT. - Scripting - Unity Discussions
July 20, 2022 - So guys, I was trying to turn a float into an int, so I did the following: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MuniçãoLoja : MonoBehaviour { public GameObject municao; private Munição m; public Animator anim; public GameObject lojaModificadorTiro; [Header("Componentes")] public int CoinsPlayer; public float valorVenenoFloat = 15; public int valorVenenoInt; public Text valorVe...
🌐
Unity
discussions.unity.com › archived forums › questions & answers
Possible to convert a Float into an Int? - Questions & Answers - Unity Discussions
April 7, 2011 - Hello, I have a value that is being passed onto another script in a float format. I want to place this value as a GUI text, but as its in a float, I get a load of ugly numbers after a decimal. How can I convert this into an Int (or a solid number). I dont want to change the value variable from : float it :int.
🌐
Vector Focus
blog.vector-focus.com › homepage › converting float to int in unity
Converting Float to Int in Unity - Blog Vector Focus
May 27, 2024 - To convert a float to the smallest integer, you have two options: you can either perform a direct cast to int or use the “ToInt32” method from the Convert class. Depending on your needs, you can also use “ToInt64” or “ToInt16”. using ...
🌐
YouTube
youtube.com › gdt solutions
How to CONVERT FLOAT TO INT in Unity - YouTube
In this video we see four methods to convert float variables to integer in Unity.First we see how to make a type casting, an operation that removes the decim...
Published: December 10, 2023
Views: 1K
Find elsewhere
🌐
Unity
discussions.unity.com › scripting
How to switch int to floats(if possible) - Scripting - Unity Discussions
November 15, 2020 - I started created games and I’m new to coding. I was following some tutorials on how to make health for a character for a game. One thing I wanted to add was a health bar. The tutorial for taking damage and health of the character uses floats and the one for the health bar uses integers.
Top answer
1 of 2
73

Firstly, there are integers and floating-point numbers. Integers are always whole numbers, such as 0, 1, -32, 42 and 1337. On the other hand, floating-point numbers can have a fractional part: 0, 1, -32.1, 42.7 and 123.456788 are all valid floating-point numbers.

When converting between integers (int) and floating-point (float) numbers, you can do this:

int someInt = 42;
float someFloat = someInt;  // 42.0f

But you can't do this:

float someFloat = 42.7f;
int someInt = someFloat;    // ?

The reason the first conversion is possible, is that converting the integer number (int) to a floating-point number (float) does not change the number. It is a safe conversion, and therefore can be done implicitly.

The reason the second conversion is not allowed, is that converting the floating-point number (which may have a fractional part) to an integer number (that never has a fractional part) must drop the fractional part of the number, i.e. it becomes a different number. This is not safe, and can therefore only be done explicitly.


To explicitly convert one type of number to another, you use a cast. That's the parentheses before the number with the type of the number that you want to convert it to.

float someFloat = 42.7f;
int someInt = (int)someFloat;               // 42

Note that the fractional part of the floating-point number was dropped. It's as if it has been rounded towards zero. If you want to round the floating-point number to the nearest whole number, use the Math.Round method.

float someFloat = 42.7f;
int someInt = (int)Math.Round(someFloat);   // 43
2 of 2
17

Try this :

int numInt = (int)Math.Ceiling(numFloat);

msdn documentation

You may want Math.Round() or Math.Floor() by the way.

Example :

float numFloat = 1.5f;
int testCeiling = (int)Math.Ceiling(numFloat);
int testFloor = (int)Math.Floor(numFloat);
int testRound = (int)Math.Round(numFloat);

Console.WriteLine("testCeiling = {0}", testCeiling.ToString());
Console.WriteLine("testFloor = {0}", testFloor.ToString());
Console.WriteLine("testRound= {0}", testRound.ToString());

output :

testCeiling = 2
testFloor = 1
testRound= 2
🌐
Unity
discussions.unity.com › scripting
Float and Int need help! - Scripting - Unity Discussions
April 14, 2020 - Hi im following the tutorial to attack enemies with this tutorial and the Health(bar) system from this tutorial But in the Attack Enemies video he uses after public “float” but in the Health Bar system he uses “Int” my scripts don’t match… I wonder if there is a word that combines ...
🌐
Unity
discussions.unity.com › scripting
"int to float" conversion when I cannot find one - Scripting - Unity Discussions
July 21, 2015 - On line 22, I receive the error “Cannot implicitly convert type float' to int’. An explicit conversion exists” ; when, from what I understand, the MathF.Round() converts float to nearest int. I have only been using Unity3D for the past 5 days, which is also the length of time I have been ...
🌐
Unity
discussions.unity.com › getting started
How to convert float to int for display as string? - Getting Started - Unity Discussions
July 10, 2018 - [FIXED] Hello sir, I’m a newbie and sorry if this is a stupid question. I try to display character health by using “ToString” from the character health source but the problem is it comes with a lot of float number like 50.0545454352435 so yeah, very messy.
🌐
Unity
discussions.unity.com › scripting
How to change float to int - Scripting - Unity Discussions
February 1, 2017 - Hello, I want to change sprite depend on angle. But It’s angle is float and sprite list is Integer.
🌐
Unity
discussions.unity.com › scripting
Force a float into an integer value - Scripting - Unity Discussions
June 17, 2019 - Very easy and quick question. I want characters to increment a 10% of their current health when leveling up. Sometimes that number is not an integer (I need them to be integer for something very important). Can I make it take the 10% of the number and force that number to take an equivalent as an int number?
🌐
Unity
discussions.unity.com › archived forums › questions & answers
Turn float to int - Questions & Answers - Unity Discussions
October 9, 2014 - I multiplied a float with Time.deltaTime like: SomeFloat -= 0.001 * Time.deltaTime And i’m showing the “SomeFloat” float graphicaly with GUI.Label, and it works like it’s supposed to, reduces by -0.001 every second… I’m…
🌐
Unity
discussions.unity.com › scripting
What is faster to convert float to int ? (int) randomFloat or Mathf.RoundToInt(randomFloat) - Scripting - Unity Discussions
Hey ! I was wondering if there’s a différence between these two methods to convert float to int and if there is, which one is faster ? Thanks
Published: September 16, 2014