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

coerce numbers when appropriate #143

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

coerce numbers when appropriate #143

wants to merge 1 commit into from

Conversation

philhofer
Copy link
Member

Addresses some comments in #134
@client9

Review on Reviewable

@klauspost
Copy link
Collaborator

@philhofer I got a bit nerd-sniped by this.

It seems like we can also return float values that map exactly to an integer - meaning a value that is exactly the integer without any rounding.

// isExactInt will return true if the number represents an integer value.
// NaN, Inf returns false.
func (n *Number) isExactInt() bool {
	var eBits int // Exponent bits
	var mBits int // Mantissa bits

	switch n.typ {
	case InvalidType, IntType, UintType:
		return true
	case Float32Type:
		eBits = 8
		mBits = 23
	case Float64Type:
		eBits = 11
		mBits = 52
	default:
		return false
	}
	// Calculate float parts
	exp := int(n.bits>>mBits) & ((1 << eBits) - 1)
	mant := n.bits & ((1 << mBits) - 1)
	if exp == 0 && mant == 0 {
		// Handle zero value.
		return true
	}

	exp -= (1 << (eBits - 1)) - 1
	if exp < 0 || exp == 1<<(eBits-1) {
		// Negative exponent is never integer (except zero handled above)
		// Handles NaN (exp all 1s)
		return false
	}

	if exp >= mBits {
		// If we have more exponent than mantissa bits it is always an integer.
		return true
	}
	// Check if all bits below the exponent are zero.
	return bits.TrailingZeros64(mant) >= mBits-exp
}

It doesn't check if the value will under/overflow a given integer size, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants