英文:
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:",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
得分: 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("%.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论