Skip to content

Unmarshal to float32 yields different output than encoding/json #884

Description

@bimoadityar

Describe the bug

Unmarshaling some values to float32 yields different output than encoding/json.

To Reproduce

Run the following code:

import (
	"encoding/json"
	"testing"

	"github.com/bytedance/sonic"
	"github.com/stretchr/testify/assert"
)

func TestPrecision(t *testing.T) {
	b := []byte("7.328900098800659")
	var js float32
	var ss float32
	_ = json.Unmarshal(b, &js)
	_ = sonic.Unmarshal(b, &ss)
	assert.Equal(t, js, ss) // js == 7.3289, ss == 7.3289003
}

Expected behavior

For sonic to return output exactly the same as encoding/json.
I am guessing it is because sonic seems to unmarshal to float64 before casting the value to float32, which somehow seems to give less precision than parsing the value directly to float32.

Sonic version:

v1.14.2-0.20251010110621-72bd4caf6fb6

Environment:

GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/bimoadityar/.cache/go-build"
GOENV="/home/bimoadityar/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/bimoadityar/.go/pkg/mod"
GOOS="linux"
GOPATH="/home/bimoadityar/.go"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/home/bimoadityar/.config/spkit/bin/sdk/go1.23.12"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/home/bimoadityar/.config/spkit/bin/sdk/go1.23.12/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="go1.23.12"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/bimoadityar/Documents/bimo-test-2/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build1204808054=/tmp/go-build -gno-record-gcc-switches"

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghelp wantedExtra attention is needed

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions