Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

value: add BigInt.Float64 for Go 1.20 and older #152

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions value/bigint_go120.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build !go1.21

package value

import "math/big"

// Float64 returns the float64 value nearest x,
// and an indication of any rounding that occurred.
//
// The implementation is backported from Go 1.21.0's
// math/big.Int.Float64 implementation.
func (i BigInt) Float64() (float64, big.Accuracy) {
n := i.Int.BitLen()
if n == 0 {
return 0.0, big.Exact
}

// Fast path: no more than 53 significant bits.
if n <= 53 || n < 64 && n-int(i.Int.TrailingZeroBits()) <= 53 {
f := float64(i.Int.Uint64())
if i.Int.Sign() == -1 {
f = -f
}
return f, big.Exact
}

return new(big.Float).SetInt(i.Int).Float64()
}