dongqiao1151 2016-02-03 17:25
浏览 63
已采纳

Golang更改浮点数的XML元帅格式

When I marshal float64 to an xml file:

type X struct {
    Value float64 `xml:",attr,omitempty"`
}
var x X
x.Value = 1000000.04

I get value like:

<X Value="1.00000004e+06"></X>

How to change the output format, such that the full value (1000000.04) is written (and the omitempty tag is still working)?

  • 写回答

1条回答 默认 最新

  • dongle7882 2016-02-03 17:32
    关注

    You can create your own number type that marshals the way you like it:

    type prettyFloat float64
    
    func (f prettyFloat) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
        s := fmt.Sprintf("%.2f", f)
        return xml.Attr{Name: name, Value: s}, nil
    }
    

    Playground: http://play.golang.org/p/2moWdAwXrd.

    EDIT: ,omitempty version:

    type prettyFloat float64
    
    func (f prettyFloat) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {
        if f == 0 {
            return xml.Attr{}, nil
        }
        s := fmt.Sprintf("%.2f", f)
        return xml.Attr{Name: name, Value: s}, nil
    }
    

    Playground: http://play.golang.org/p/myBrjGGSJY.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python