Casting

Feb 12, 2012 at 2:45 AM
Edited Feb 12, 2012 at 11:49 AM

Right, I've been having trouble when converting doubles to integers:

int someInt = 20;
double somedouble = (double)someInt;

This seems to work when I write the values to the console, but when I try this:

double somedouble = 20.2;
int someint = (int)somedouble;

It doesn't work.

I've tried making a function that rounds a double, converts that to a string, then returns the integer part, but it didn't work.

This is the conversion function I used, it works in a normal console application in .NET, I'm guessing that Double.toString() is not implemented yet.

public static int Round(double n)
{
     string number = Math.Round(n).ToString();
     return int.Parse(number);
}

Any help?

Coordinator
Feb 12, 2012 at 3:29 PM
> Right, I've been having trouble when converting doubles to integers:
>
> int someInt = 20;
> double somedouble = (double)someInt;
>
> This seems to work when I write the values to the console, but when I
> try this:
>
> double somedouble = 20.2;
> int someint = (int)somedouble;
>
>
> And it is not like Math.Round() is of any use, as it only rounds the double.
>
> I've tried making a function that rounds a double, converts that to a
> string, then returns the integer part, but it didn't work effectively.

Its probably an issue with the compiler. Try Math.Truncate, but it might
not be plugged....
Developer
Feb 12, 2012 at 4:49 PM

casting from a double to an integer should be truncating the decimal part of it. Also, uint, long, and ulong to float/double don't currently work, due to the complexity of doing so :P (long might actually work, but large values for uint & ulong definately won't)  We also still need to fix the (branch) comparisons for long and ulong.

Feb 12, 2012 at 10:01 PM

Yeah, Math.Truncate is not plugged, but I think it may be down to the fact every time I tried to convert, I also used Math.Round to get the best accuracy. I'll try casting without Math.Round.