Ask questionsv3: Can Encode() write 1.0 float as 1.0 (instead of 1)

When printing a float with just a zero after decimal point, the decimal point and the zero is not printed.

func main() {
	m := map[string]interface{}{
		"a": 1.0,
	var buf bytes.Buffer
	enc := goyaml.NewEncoder(&buf)
	if err := enc.Encode(m); err != nil {
	if err := enc.Close(); err != nil {
	fmt.Println(string(buf.Bytes()))  // Output: a: 1
        // Expected: a: 1.0

I see that internally it does the formatting using strconv.FormatFloat() here. Couldn't figure out a way to do it through strconv.FormatFloat() (convert 1 (float) to "1.0"). If it's possible can it be added to the library?


Answer questions niemeyer

You can use yaml.Node directly or via a yaml.Marshaller if you want to fine tune the encoded string or just preserve the original string value. In the specific example you're using a map of interface{}, with a plain 1.0, so it's using the default behavior of the library which is to encode into the shortest human representation of the number.

I realize this may sound a bit controversial because 1 and 1.0 are two different types as far as the yaml specification is concerned, but this was a conscious choice made early on, based on the idea that the only reason one would pick yaml is because it's human-friendly to read and write, and having software with diverging behavior for 1 and 1.0 would go against that.

If you have further questions or more details about your use case, happy to continue the conversation here.


Related questions

v3 panics on bad input hot 1
v3 equivalent of v2's MapSlice and MapItem? hot 1
unmarshal with comments provide wrong structure hot 1
Head comments in list elements misplaced hot 1
Github User Rank List