Skip to content

coerce numbers when appropriate#143

Closed
philhofer wants to merge 1 commit intomasterfrom
more-number
Closed

coerce numbers when appropriate#143
philhofer wants to merge 1 commit intomasterfrom
more-number

Conversation

@philhofer
Copy link
Member

Addresses some comments in #134
@client9

Review on Reviewable

@philhofer philhofer mentioned this pull request Apr 13, 2016
@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.

klauspost added a commit to klauspost/msgp that referenced this pull request Aug 27, 2025
klauspost added a commit that referenced this pull request Aug 28, 2025
* Add `Coerse` functions to `Number`

Expands/replaces #143
@klauspost
Copy link
Collaborator

Added in #404 with float coercion.

@klauspost klauspost closed this Aug 28, 2025
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