bytedance/sonic

Unmarshal to float32 yields different output than encoding/json

Ouverte

#884 ouverte le 3 déc. 2025

 (3 commentaires) (1 réaction) (0 personne assignée)Go (454 forks)github user discovery
bughelp wanted

Métriques du dépôt

Stars
 (9 488 étoiles)
Métriques de merge PR
 (Merge moyen 12j 6h) (3 PRs mergées en 30 j)

Description

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"

Guide contributeur