Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pgtype.Numeric to float conversion

Tags:

go

pgx

I have an app that uses interfaces to get a variable number of columns from a postgresql database. It uses a dynamic struct of type map[string]interface{} for the data type for the query to scan into and it is all working to the point where the data is coming back fine, I can decode the column names into keys on the map and the data is able to be converted to either time.Time (for the time stamps) or pgtype.Numeric for the other fields.

This is great... BUT. I have been totally unable to get the pgtype.Numeric results to convert to float32 or Int results.

I can pull apart the pgtype.Numeric returns and print them out (for example)

Turbine, Timestamp, WindSpeed, WindDir, Power
   t017,2024-02-15 18:20:00 +1100 AEDT,{892 -2 2 false none},{7200 -2 2 false none},{226391 -2 2 false none}

But, try as I might I am totally unable to go from pgtype.Numeric to a base type.

There are directions for using set to make the pgtype.Numeric, but I've tried .Scan, and .Get and straight up casts and have not had any joy at all at getting the number back.

This MUST be easy... but I cannot work it out.

var floatval float32
err := pgNumeric.Scan(&floatval) just returns 0 every time.

What have I missed?

like image 654
Peter Nunn Avatar asked Jul 23 '26 21:07

Peter Nunn


1 Answers

It seems there is an AssignTo method on the pgtype.Numeric:

var f float64
err := pgNumeric.AssignTo(&f)

It checks the given input type and fills the variable with it's internal value. Here is a link to the implementation.

Scan does the parsing of the DB value into the Numeric variable.

like image 198
TehSphinX Avatar answered Jul 25 '26 20:07

TehSphinX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!