Posted by
Herbie on
Nov 21, 2020; 1:09pm
URL: http://imagej.273.s1.nabble.com/String-format-tp5024199p5024220.html
In case it matters, the following macro function (that works similarly
in Java) does it in a handcrafted fashion:
///////
requires("1.53f");
string = preZeros( d2s( PI, 5 ), 3 );
print( string );
function preZeros( inStr, n ){
if ( inStr.contains( "." ) ) {
str = split( inStr, "[.]" );
inStr = str[0];
dec = "." + str[1];
}
while ( inStr.length() < n ) inStr = "0" + inStr;
return inStr + dec;
}
//////
Have fun
Herbie
::::::::::::::::::::::::::::::::::::::::::
Am 21.11.20 um 13:33 schrieb Stein Rørvik:
> 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&data=04%7C01%7Cstein.rorvik%40sintef.no%7Ce5f8a69be3104cb30bda08d88bda59ba%7Ce1f00f39604145b0b309e0210d8b32af%7C1%7C1%7C637413117218634903%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=Zn5pKbxK4MklXs3rgwo1Xjs4RtWJ9OBnnD7iezL%2BIZQ%3D&reserved=0>
> --
> ImageJ mailing list:
http://imagej.nih.gov/ij/list.html>
--
ImageJ mailing list:
http://imagej.nih.gov/ij/list.html