Search code examples
xmlgoformatmarshalling

Golang change xml marshal format of float


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)?


Solution

  • 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.