[英]Message format in java and how to replicate the same in Golang
Here's the Java code: 这是Java代码:
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: 我在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? {0,number,#}
什么意义?如何在Go中获得相同的内容?
This is detailed at java.text.MessageFormat
. 这在java.text.MessageFormat
有详细说明。 The string you pass to MessageFormat.format()
is a pattern . 传递给MessageFormat.format()
的字符串是一种模式 。 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. 0
是要格式化的值的参数索引。
number
is a format type, and #
is a format style, more specifically a subformat pattern . number
是格式类型, #
是格式样式,更具体地说是子格式 。 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
. 在#
子格式在描述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). 它只是意味着不使用小数位,只显示为整数,如果它不是整数,它将被舍入(使用RoundingMode.HALF_EVEN
模式)。
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. 在Go中格式化整数,您可以像使用%d
动词一样使用,这将为整数生成相同的输出格式。 If the number is a floating point number, this won't work ( %d
can only be used for integers). 如果该数字是浮点数,则不起作用( %d
只能用于整数)。 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
. 如果数字是浮点数,请使用%f
动词,更具体地说%.0f
告诉它舍入为整数,或者使用最短格式%.f
。
Also your Java version puts the last argument in double quotes, so you should do the same in Go. 此外,您的Java版本将最后一个参数放在双引号中,因此您应该在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 ): 这将输出(在Go Playground上尝试):
0,5bb2b35c67525f9e845648df370652b8,Vm:vm-289,1.1.1.1:113,"ABC-Testvm-1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.