Login  Register

Re: String.format

Posted by Stein Rørvik on Nov 21, 2020; 12:33pm
URL: http://imagej.273.s1.nabble.com/String-format-tp5024199p5024219.html

Peter,

If what you want to do is to zero pad an integer,
you can do this by formatting it as a float specifying zero decimals:

        s = String.format("%04.0f", 13);
        print(s);

prints 0013

        str = String.format("%09.5f", PI);
        print(str);

prints 003.14159

The last syntax is useful as it allows for more complex number formatting.
You can for example pad with spaces instead:
        str = String.format("% 9.5f", PI);

Apparently, String.format does not work as expected with numbers if you omit the .n decimal specification in the format string.

The IJ.pad() function is easier to use, but only works with integers.

Stein

-----Original Message-----
Sent: 18. november 2020 16:54
Subject: String.format

Hi,
I would like to execute the macro function:

s = String.format("%04d", 13);
print(s);

but I get the error message
"java.util.IllegalFormatConversionException: d != java.lang.Double in line 1:"
"s = String . format ( "%04d" , 13 <)> ;"

If the number is float and not integer It's working:

s = String.format("%04f", 13.0);
print(s);

Could this be a bug?

--
ImageJ mailing list: https://eur03.safelinks.protection.outlook.com/?url=http%3A%2F%2Fimagej.nih.gov%2Fij%2Flist.html&amp;data=04%7C01%7Cstein.rorvik%40sintef.no%7Ce5f8a69be3104cb30bda08d88bda59ba%7Ce1f00f39604145b0b309e0210d8b32af%7C1%7C1%7C637413117218634903%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&amp;sdata=Zn5pKbxK4MklXs3rgwo1Xjs4RtWJ9OBnnD7iezL%2BIZQ%3D&amp;reserved=0

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html