Topic outline

  • Decimal numbers (desimaaliluvut)

    So far we’ve used only int type for our calculations. Often the precision is not enough: for example if you divide one by two you get zero instead of 0.5. For more precision we can employ floating point numbers (liukuluvut), which can store decimal numbers. Instead of int, declare your variable float:

    float mynumber;

    An example illustrating the difference between the two: intvsfloat.pde

    Type conversion (tyyppimuunnos)

    Processing is very strict about mixing variables and functions of different types. You can’t directly assign a variable of type float into an int. For example random numbers in Processing are floats, and that’s why you can’t assign them to int variables without conversion. Fortunately, type conversion is easy to do:

    int a;
    float b=random(100);

    A few more conversions here: typeconversion.pde

    Boolean: true or false

    Often it’s handy to have variables that contain yes/no values. For them we have type boolean, which can only have values true or false. You can’t do any mathematical calculations with booleans.

    boolean truth=true;

    One example of booleans that we've already used is mousePressed. Since booleans are either true or false they can be used as conditions: if(mousePressed)

    Strings (merkkijonot)

    A new type coming up. Ints and floats let us use numbers, but there’s many situations when other types are needed. Textual information can be stored in a String. Two common use cases for strings are user-entered data and reading a text file. You declare a string as any other variable.

    String mytext;

    Assignment is the same. A string is enclosed in double quotes:

    mytext="Never gonna give you up";

    You can "add" a string after another with the plus sign (+). To convert a number into a string, use the function str() like in the examples above.

    Displaying text

    We’ve output text with println already, but to display text inside the sketch window we need to use PFont together with loadFonttextFont and text. Processing has its own bitmap font format. Save your sketch first and then click Tools – Create Font. How to do all of it: graphicaltext.pde.


    Make a crosshair that follows the mouse. In addition, display the current coordinates in the sketch window like this:


    Example solution: crosshair.pde