Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go - Efficient way of converting float to pgtype.Numeric

Tags:

go

pgx

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.

like image 335
KarlsMaranjs Avatar asked Oct 18 '25 19:10

KarlsMaranjs


1 Answers

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.

like image 117
Mohamed Sohail Avatar answered Oct 20 '25 10:10

Mohamed Sohail