Go - Efficient way of converting float to pgtype.Numeric

556 views Asked by At

I am using github.com/jackc/pgx/v5. In v4 we had a Numeric.Set() method that we could use in the following way:

var num &pgtype.Numeric{}
num.Set(4.35)

However in v5 there is no more Set() method. See repo here.

So, how do we create Numeric objects in v5? Are we supposed to use this way:

   
    // This is equivalent to 5.43
    num := pgtype.Numeric{
    Int: big.NewInt(543), 
    Exp: -2, 
    Status: pgtype.Present
    }

Is there any other way around? Of course, other than implementing it myself. Don't take me wrong I have nothing against writing the code, I just want to know if there's already a way to do this and if I am on the right track.

1

There are 1 answers

4
Mohamed Sohail On

Looking at the tests, you could still use Scan:

package main

import (
    "log"

    "github.com/jackc/pgx/v5/pgtype"
)

func main() {
    var x pgtype.Numeric

    if err := x.Scan("4.35"); err != nil {
        log.Panic(err)
    }

    log.Printf("x: %+v", x)
}

Your use case seems to be quite unique. Typically this is used to convert the Postgres NUMERIC response to compatible go types.