Create filename from variables

I want to save an image from the display window using save().

For example:

I want, though, to create the filename using the values of some variables in my sketch.


int var1 = 290;
float var2 = 2.000;
float var3 = 8.000;

…some code


Is this possible?

Yes, the filename is a String. Just convert any variable you want into a String, then stick the strings together and save to that:

String filename = str(var1) + "_" + str(var2) + "_" + str(var3) + ".tif";


Note that if you want to format the floats in specific ways – so that you don’t get 3.999999987 as part of your filename – you can use number formatting functions, for example: nfs(var2, 0, 3);


Also just noting that, for the simple case of a sequence of numbered (not for your needs, but for others who may read this thread in the future):

saveFrame() also has a built-in method for numbering frames with the zero-padded frameCount:

// Saves each frame as line-000001.png, line-000002.png, etc.

1 Like

Thank you so much.
On the use of nfs() and using your example,

float var2 = 3.999999987;

String vs = nfs(var2, 0, 3); // gives 4.000

The zero for the number of digits to the left of the decimal point does not seem to do anything. Is this left value more for putting leading zeros before some numbers so they align?

That is correct, it is for zero-padding. So, if you know your numbers will range from 0-64, and you want .0 precision, then:

String vs = nfs(var2, 2, 1);

Will give you outputs like 00.1, 01.2, or 12.3.


1 Like