- Home /
Need decimals of a division of Ints
Hi,
I have two ints and dividing them I need to obtain a float. But if I use the normal division I obtain a int without decimals, what can I do?
Lot of thanks
Answer by oxium · May 23, 2011 at 07:20 AM
just cast in float before you do the division. something like that :
int i1 = 10;
int i2 = 3;
float f = ((float) i1) / ((float) i2);
then f will be equal to 3.33333 (instead of 3 if you change the type of f to be integer)
It gives me this error:
Assets/nuevo/Scripts/Progressive Health Bar.js(35,28): UCE0001: ';' expected. Insert a semicolon at the end.
Exactly in : float f = ((float) i1) / ((float) i2);
Answer by KeithK · May 23, 2011 at 07:20 AM
Hey Infinity
What's happening is because you dividing an int by another int, it is assumed you would like an int as your answer type.
To get your result as a float, just cast your first int to a float like so:
float answer = ((float)intOne) / intTwo;
This is then seen as a float being divided and so implicit conversions to float from all non-float types will occur.
It gives me the following error when I use it:
Assets/nuevo/Scripts/Progressive Health Bar.js(35,28): UCE0001: ';' expected. Insert a semicolon at the end.
The error is exactly in this line
Oh damn it. Sorry, forgot a set of brackets. Updated the answer even though this question is marked as answer.
I think it's because Infinity expects a JS solution while you and oxium provide C# solutions. I think you could just replace the initial types from int and float to var.
And how I can use it on javascript? I can't change the main type of the variables >__<
Answer by SisterKy · Jan 11, 2013 at 12:13 PM
This is an old question but since it was the first to come up when I googled I'd like to add the js-solution
var c : float = parseFloat(a) / b;
or
var c : float = (a+0.0) / b;
Additional Info:
Casting in UnityScript is usually done through "variable name" as "classname" ,
but since int/float are primitives, this WON'T work:
a as float
Source (Answer by Eric, additional Info by Dreamora)
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
How do i divide int by float? 1 Answer
Can I create a list with an int/float and a string? C# 2 Answers
Whole Numbers Divide Incorrectly....BUG? 0 Answers
Are float values reliable? 0 Answers