Skip to content

Commit 12a3436

Browse files
authored
Add Number.CoerceFloat (#407)
Add a convenience function to always get a number as float, even if converted. Fixes #152
1 parent 2f1ed81 commit 12a3436

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

msgp/number.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,24 @@ func (n *Number) isExactInt() bool {
314314
return bits.TrailingZeros64(mant) >= mBits-exp
315315
}
316316

317+
// CoerceFloat returns the number as a float64.
318+
// If the number is an integer, it will be
319+
// converted to a float64 with the closest representation.
320+
func (n *Number) CoerceFloat() float64 {
321+
switch n.typ {
322+
case IntType:
323+
return float64(int64(n.bits))
324+
case UintType:
325+
return float64(n.bits)
326+
case Float32Type:
327+
return float64(math.Float32frombits(uint32(n.bits)))
328+
case Float64Type:
329+
return math.Float64frombits(n.bits)
330+
default:
331+
return 0.0
332+
}
333+
}
334+
317335
// Msgsize implements msgp.Sizer
318336
func (n *Number) Msgsize() int {
319337
switch n.typ {

0 commit comments

Comments
 (0)