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 › float() but not int()
Page Index Toggle Pages: 1
float() but not int()? (Read 1022 times)
float() but not int()?
May 30th, 2010, 5:17am
 
Hello. This is my first post on discourse. Please redirect me to the proper forum if this is not the one. Thanks.

My latest little experiment is receiving strings (over a serial line). The string consists of a qualifier (one character) a colon and then a value (one or more characters [0-9]). eg: "r:279".

My code splits the string into two, using the colon as a delimiter. The first substring is a single character string. The second is a cause for headaches.

When I try to convert the string into a number, my instinct tells me to use integers, because that's what they are (to me). but this:
int value = int(telemetry[1]);
gives me zeroes every time, while this:
float value = float(telemetry[1]);
works just fine.

Please, can someone explain the difference that is obviously there, but not so to me.
Rik

Quote:
import processing.serial.*;

Serial PicPort;
String myString = null;
int cr = 13; // strings are terminated by ascii 13: carriage return aka newline

void setup() {
  //                 parent comport           baud  parity databits stopbit
  PicPort = new Serial(this, Serial.list()[0], 4800, 'N',   8,       1.0);
  myString = PicPort.readStringUntil(cr);
}

void draw() {
  while (PicPort.available() > 0) {
    myString = PicPort.readStringUntil(cr);
    if (myString != null) {
      // println(myString);
      // examples of myString: "r:259", "t:18", "t:0"
      String telemetry [] = split(myString, ":");
      String qualifier = telemetry[0];
      float value = float(telemetry[1]);  //  WHY won't this convert to int ?!?!

      //println (qualifier +"="+ value);
    }
  }
}
Re: float() but not int()?
Reply #1 - May 30th, 2010, 5:50am
 
Let's make a little simple test:
Code:
void setup()
{
String myString = "r:259\r";
String telemetry [] = split(myString, ":");
String qualifier = telemetry[0];
float value = float(telemetry[1]);
println(qualifier + "=" + value);
}

Works fine.
If I replace the floats with ints, I get zero too. If I remove the \r, both work fine.

Conclusion: float() tolerates trailing whitespace values, while int() doesn't.
Not sure if that's your problem, but it is worth checking.
Page Index Toggle Pages: 1