Skip to content

text/template: 0 divided by a negative number prints -0 instead of 0 #51770

@cmarkh

Description

@cmarkh

What version of Go are you using (go version)?

$ go version
go version go1.18 windows/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
set GO111MODULE=
set GOARCH=amd64
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=C:\Program Files\Go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:\Program Files\Go\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.18
set GCCGO=gccgo
set GOAMD64=v1
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOWORK=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -build1173738419=/tmp/go-build -gno-record-gcc-switches

What did you do?

https://go.dev/play/p/l196xxd7doS


package main

import (
	"bytes"
	"fmt"
	"log"
	"text/template"
)

func main() {
	t := template.New("e")
	t.Funcs(template.FuncMap{
		"divide": func(part, total float64) string {
			return fmt.Sprint(part / total)
		},
	})

	t, err := t.Parse(`0 / -2 using template generates: {{divide 0 -2}}`)
	if err != nil {
		log.Fatal(err)
	}

	var output bytes.Buffer
	err = t.Execute(&output, nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("0 / -2 prints: %v\n", 0/-2)
	fmt.Printf("0 / -2 prints: %v\n", 0.0/-2.0)
	fmt.Println(output.String())

	return
}

What did you expect to see?

Normally dividing 0 by a negative number (here I used 0 / -2) will print 0.

What did you see instead?

fmt.Println(0/-2) prints 0 as expected.
When I use a custom division function inside a template, 0/-2 prints -0.
0 == -0 but I don't typically see the negative version printed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions