From 249ef7272d814c6839f04fefde0bc1f92d2a57d4 Mon Sep 17 00:00:00 2001 From: Klaus Post Date: Thu, 28 Aug 2025 12:46:36 +0200 Subject: [PATCH] Add Number.CoerceFloat Add a convenience function to always get a number as float, even if converted. Fixes https://github.com/tinylib/msgp/issues/152 --- msgp/number.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/msgp/number.go b/msgp/number.go index 0035a15c..3b6588fd 100644 --- a/msgp/number.go +++ b/msgp/number.go @@ -314,6 +314,24 @@ func (n *Number) isExactInt() bool { return bits.TrailingZeros64(mant) >= mBits-exp } +// CoerceFloat returns the number as a float64. +// If the number is an integer, it will be +// converted to a float64 with the closest representation. +func (n *Number) CoerceFloat() float64 { + switch n.typ { + case IntType: + return float64(int64(n.bits)) + case UintType: + return float64(n.bits) + case Float32Type: + return float64(math.Float32frombits(uint32(n.bits))) + case Float64Type: + return math.Float64frombits(n.bits) + default: + return 0.0 + } +} + // Msgsize implements msgp.Sizer func (n *Number) Msgsize() int { switch n.typ {