Golang如何更改XML编组中浮点数的格式。

huangapple go评论76阅读模式
英文:

Golang change xml marshal format of float

问题

当我将float64编组为XML文件时:

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

我得到的值是:

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

如何更改输出格式,以便写入完整的值(1000000.04),并且omitempty标签仍然起作用?

英文:

When I marshal float64 to an xml file:

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

I get value like:

&lt;X Value=&quot;1.00000004e+06&quot;&gt;&lt;/X&gt;

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

答案1

得分: 7

你可以创建自己喜欢的数字类型的编组方式:

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.

**编辑:**带有,omitempty的版本:

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

英文:

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(&quot;%.2f&quot;, 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(&quot;%.2f&quot;, f)
	return xml.Attr{Name: name, Value: s}, nil
}

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

huangapple
  • 本文由 发表于 2016年2月4日 01:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/35183690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定