We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › How do u determine if result is a float or an int
Page Index Toggle Pages: 1
How do u determine if result is a float or an int? (Read 462 times)
How do u determine if result is a float or an int?
Dec 15th, 2008, 1:50am
 
If I divide my yPos by 5, and get a result which has a decimal point, ie a float, I want nothing to happen, if I divide the yPos by 5 and get an integer, i want something to happen.

How do I ask processing to check if a result is an integer or a float? Or a whole number or a number with decimals?

The purpose is to allow a line drawing script to work on a grid. So I only want the line to draw when it's on multiples of 5.

Thanks!
Marc
Re: How do u determine if result is a float or an
Reply #1 - Dec 15th, 2008, 1:02pm
 
is the thing you're dividing an int or a float?

the following works for integers

Code:

int y;
if ((y % 5) == 0) {
// this is true for y = 0, 5, 10...
}
Re: How do u determine if result is a float or an
Reply #2 - Dec 15th, 2008, 2:10pm
 
Actually, it works also for floats.
You can even do:
Code:
float f = 7.5;
println(f % 1.5); // Shows 0.0

Which leads to a trick to answer the title:
number % 1 == 0
is true if number is an integer (0 in the decimal part).
Re: How do u determine if result is a float or an
Reply #3 - Dec 15th, 2008, 9:16pm
 
i was told never to compare floating point numbers for equality - they just aren't accurate enough.

http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
Re: How do u determine if result is a float or an
Reply #4 - Dec 16th, 2008, 5:11pm
 
Hi
Sorry been sick with flu thus my quietness.

I was thinking the modulo could be one of the ways to work it out. I know understand it, basically it works out the remainder left after dividing something in wholes, so if that remainder is zero, it's fully divisible by it. Handy!

Thanks a bunch.
Marc


Re: How do u determine if result is a float or an
Reply #5 - Jan 29th, 2009, 7:14pm
 
what about
Code:

if (f==floor(f)) {
  ...
}


also, just semantics - i would use terms "whole" and "non-whole" because "integer" and "float" are data types, and a whole number of 3.0 is still technically a float.  mathematically it's an integer, but in programming it's not.
Page Index Toggle Pages: 1