Problem with floats

Monkey Forums/Monkey Beginners/Problem with floats

My_Fat_Fox(Posted 2014) [#1]
I have run into a problem with floats that I can't figure it out. I must be missing something very obvious and would be very grateful if someone would point it out.

If I set a variable as a float, why can't I set it to equal a fraction? If I have a variable a:Float = 0.5 that works OK, but if I try a = 4/10 it sets a to zero.

I noticed this when trying to set different alpha values for images. SetAlpha(5/10) sets the alpha to zero, while SetAlpha(0.5) works just fine. Using a variable seemed to be the answer which is where I ran into the float problem.


secondgear(Posted 2014) [#2]
You are dividing two integers, which produces an integer result. Try changing at least one of them to float: 5.0/10 or Float(5)/10


My_Fat_Fox(Posted 2014) [#3]
Thanks secondgear, problem solved. I knew it would be something obvious, but that never occurred to me.


ImmutableOctet(SKNG)(Posted 2014) [#4]
There's also the option of simply adding the ".0" suffix to the numbers. That's usually registered as a floating-point literal, so casting shouldn't be required.


My_Fat_Fox(Posted 2014) [#5]
Thanks ImmutableOctet(SKNG),

Perhaps this should be made clearer in the documentation for floats and integers, as it seems to be a unique quirk of Monkey's - I'm a veteran of various archaic versions of Basic (anyone remember Locoscript?) and more recently Visual Studio which I don't recall handling integers and floats like this. I can't be the first person to assume that d:Float = 3/4 would set the float to 0.75, not zero!

Hopefully this post will help others stuck feeling like an idiot knowing they have missed something very basic but unable to figure out what it is.

Is there a reason for this behavior (I'm thinking it's the way some platforms work) or is it just one of those things?


muddy_shoes(Posted 2014) [#6]
It's far from a Monkey quirk. Integer division producing an integer result is how it works in most mainstream languages.


My_Fat_Fox(Posted 2014) [#7]
muddy_shoes,

Thanks, now I feel even more foolish :-)

In my defense, Visual Basic doesn't do this, I just wrote a test program to check, but perhaps that's an overload.


ImmutableOctet(SKNG)(Posted 2014) [#8]
I don't know, from what a friend of mine was saying, Visual Basic's compiler's pretty bad. He was mentioning bugs with its logarithm implementation, but the standard .NET implementation worked fine. I've been meaning to try VB, but considering I know my way around C# well enough, I haven't really needed to.


My_Fat_Fox(Posted 2014) [#9]
VB does seem to have a lot of bugs. I wish I had just learned C# instead.


ziggy(Posted 2014) [#10]
Legacy -vb is horrible. Modern vb.net is as good as C#, and they share most of the same code base. And this comparison will be completely out when roslyn comes out. http://msdn.microsoft.com/en-US/vstudio/roslyn.aspx