Conversation
Closed
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
Expands/replaces tinylib#143
klauspost
added a commit
that referenced
this pull request
Aug 28, 2025
* Add `Coerse` functions to `Number` Expands/replaces #143
Collaborator
|
Added in #404 with float coercion. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Addresses some comments in #134
@client9