java - Why does `%4.` add space to my number? -
java - Why does `%4.` add space to my number? -
i have code:
private string padwithzerorighttoperiod(string serverformat, float unformattednumber, int index) { int ndigits = getnumberofdigitsafterperiod(serverformat); string floatingformat = "%4." + ndigits + "f"; string formattedprice = string.format(floatingformat, unformattednumber);
when called unformattednumber
beingness 846
, why result " 846"
(a space , 3 digits)?
what %4.
mean?
the docs string.format
refer this documentation on format strings, says:
the format specifiers general, character, , numeric types have next syntax:
%[argument_index$][flags][width][.precision]conversion
the optional argument_index decimal integer indicating position of argument in argument list. first argument referenced "1$", sec "2$", etc.
the optional flags set of characters modify output format. set of valid flags depends on conversion.
the optional width positive decimal integer indicating minimum number of characters written output.
the optional precision non-negative decimal integer used restrict number of characters. specific behavior depends on conversion.
the required conversion character indicating how argument should formatted. set of valid conversions given argument depends on argument's info type.
from illustration output, appears getnumberofdigitsafterperiod
returing 0
, format string %4.0f
. so:
$
after 4
) it has width (4
) it has precision (0
) and of course of study has conversion (f
) so 846 output " 846"
because width 4. width in question total number of characters output. here's different example: live copy
public class illustration { public static void main(string args[]) { system.out.println(string.format("%8.2f", 846.0)); system.out.println(string.format("%8.2f", 42.4)); } }
output:
846.00 42.40note each of 8 characters long.
java string formatting format string-formatting
Comments
Post a Comment