How do I match a float32? #206
-
Hi, I have a
and then using it as
Is there a way around this? Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I ended up figuring something out that seems to work for me. I add the following to my database access code: // Type wrappers for help with pgxmock unit tests
type f32 struct {
v float32
}
func (f *f32) Scan(value any) error {
v, ok := value.(float64)
if !ok {
return fmt.Errorf("could not assert %v was of type float64", value)
}
f.v = float32(v)
return nil
}
func (f f32) Value() (driver.Value, error) {
return float64(f.v), nil
} Now I can do things like: var myRealVal f32
for rows.Next() {
err := rows.Scan(&myRealVal)
// ...
}
// now I can access my float32 value by doing something like
fmt.Println(myRealVal.v) And in my test code I can check for the values by including the following in a const fpdelta float64 = 1e-6 // good enough for our fairly rough purposes
func (f f32) Match(v any) bool {
vf32, ok := v.(f32)
if !ok {
return false
}
return math.Abs(float64(f.v)-float64(vf32.v)) < fpdelta
} which allows me to do things like rows := mock.NewRows([]string{"my_real_val"}).AddRow(f32{1.5})) and now as long the difference between my expectation and the actual value is < Please note: I have an understanding that comparing IEEE 754 floating point numbers (used by Also, I needed to use Thank you. |
Beta Was this translation helpful? Give feedback.
-
Why not just type FloatArgument float64
const epsilon = 0.000001
func (a FloatArgument) Match(v interface{}) bool {
f, ok := v.(float64)
if !ok {
return false
}
return math.Abs(f-float64(a)) <= epsilon
} |
Beta Was this translation helpful? Give feedback.
Why not just