String formatting

I THINK the following will work. I don’t know if you need the “$” characters or not.

val outStr = String::format("%1$02d %2$02d:%3$02d:%4$02d",
                                       (MySetpoint.state as DecimalType).intValue,
                                       (MyHours.state as DecimalType).intValue,
                                       (MyMinutes.state as DecimalType).intValue,
                                       (MySeconds.state as DecimalType).intValue)

I’ve made up the names of your Items above of course.

What this does is create a formatted String using the Java format syntax. You should have at least a passing familiarity with this as it is the same syntax used to format Item’s labels in the Sitemap and Items files (the stuff in the [ ]).

So the above String breaks down as follows:

%1 -> The first argument
$ -> Start of the formatting string that will apply to the %1
0 -> zero pad numbers that are smaller than the number of digits specified
2 -> always print at least two digits
d -> treat the value as a integer

So %1$02d means treat the first argument as an integer, print two digits and if the number is less than ten zero pad it so it is two digits. So %2$02d means do the same thing but with the second argument, and so on.

The syntax is documented here, but it is quite extensive and difficult to read if you are in a hurry.

6 Likes