6. Types and conversions

Let’s start with a nice little trick: instead of running your sketch, present it to make it fullscreen (shift-command-r).

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 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=0;
float b;

A few more conversions here: typeconversion.pde

One type more

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;

Displaying text

We’ve output text with println already, but to display text inside the sketch window we need to use PFont together with loadFont, textFont 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. A bit more advanced: graphicalnumbers.pde

Sample project

Finally, let’s make a complete program that puts everything we’ve learned so far into use. First, we start by thinking of the needs and requirements, then proceed to designing the overall structure of the sketch, and only after that we start typing anything — do the same with your exercise task! paintprogram.pde

This entry was posted in Processing. Bookmark the permalink.