Here's the Java code:
AtomicInteger obIndex = new AtomicInteger(0);
MessageFormat.format("{0,number,#},{1},{2},{3},\"{4}\"",
obIndex.getAndIncrement(),
"5bb2b35c67525f9e845648df370652b8",
"Vm:vm-289",
"1.1.1.1:113",
"ABC-Testvm-1");
Output:
0,5bb2b35c67525f9e845648df370652b8,Vm:vm-289,1.1.1.1:113,"ABC-Testvm-1"
I tried this in Go:
value := fmt.Sprintf("%d,%s,%s,%s,%s",
0,
"5bb2b35c67525f9e845648df370652b8",
"Vm:vm-289",
"1.1.1.1:113", "ABC-Testvm-1")
fmt.Println(value)
Which outputs:
0,5bb2b35c67525f9e845648df370652b8,Vm:vm-289,1.1.1.1:113,ABC-Testvm-1
What is the significance of {0,number,#}
and how can I get the same in Go?
This is detailed at java.text.MessageFormat
. The string you pass to MessageFormat.format()
is a pattern. A pattern consists of format elements. The form of a format element is:
FormatElement:
{ ArgumentIndex }
{ ArgumentIndex , FormatType }
{ ArgumentIndex , FormatType , FormatStyle }
So in the first format element:
{0,number,#}
0
is the argument index whose value to format.
number
is a format type, and #
is a format style, more specifically a subformat pattern. This means the argument will be formatted using a subformat of:
new DecimalFormat(subformatPattern, DecimalFormatSymbols.getInstance(getLocale()))
The #
subformat is described at java.text.DecimalFormat
. It simply means to not use fraction digits, only display it as an integer, and if it is not an integer, it will be rounded (using the RoundingMode.HALF_EVEN
mode).
In Go to format an integer number, you may simply use the %d
verb as you did, which will yield the same output format for integer numbers. If the number is a floating point number, this won't work (%d
can only be used for integers). If the number is a floating point number, use the %f
verb, more specifically %.0f
to tell it to round to an integer, or the shortest form %.f
.
Also your Java version puts the last argument in double quotes, so you should do the same in Go.
value := fmt.Sprintf("%d,%s,%s,%s,\"%s\"",
0,
"5bb2b35c67525f9e845648df370652b8",
"Vm:vm-289",
"1.1.1.1:113", "ABC-Testvm-1")
fmt.Println(value)
This will output (try it on the Go Playground):
0,5bb2b35c67525f9e845648df370652b8,Vm:vm-289,1.1.1.1:113,"ABC-Testvm-1"