bytedance/sonic

Unmarshal to float32 yields different output than encoding/json

开放

#884 创建于 2025年12月3日

 (3 条评论) (1 个反应) (0 位负责人)Go (454 个派生)github user discovery
bughelp wanted

仓库指标

星标
 (9,488 个星标)
PR 合并指标
 (平均合并 12天 6小时) (30 天内合并 3 个 PR)

描述

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"

贡献者指南