duanchi4544 2018-10-08 14:08
浏览 20
已采纳

Java中的消息格式以及如何在Golang中复制消息格式

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?

  • 写回答

1条回答 默认 最新

  • douzui6173 2018-10-08 15:01
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题