Home > database >  How to compare two Mongodb primitive type Decimal128 in go
How to compare two Mongodb primitive type Decimal128 in go

Time:12-24

valueA, _ := primitive.ParseDecimal128("123.12")
valueB, _ := primitive.ParseDecimal128("123.00")

how to calculate valueA < valueB?

CodePudding user response:

I found an answer thanks to @Matteo

There is a function converting Decimal128 to BigInt.

and BigInt available to compare

func compareDecimal128(d1, d2 primitive.Decimal128) (int, error) {
    b1, _, err := d1.BigInt()
    if err != nil {
        return 0, err
    }
    b2, _, err := d2.BigInt()
    if err != nil {
        return 0, err
    }
    return b1.Cmp(b2), nil
}

CodePudding user response:

Looking in the test here:

func compareDecimal128(d1, d2 primitive.Decimal128) bool {
    d1H, d1L := d1.GetBytes()
    d2H, d2L := d2.GetBytes()

    if d1H != d2H {
        return false
    }

    if d1L != d2L {
        return false
    }

    return true
}
  • Related