如何在Go语言中比较两个MongoDB原始类型Decimal128?

huangapple go评论69阅读模式
英文:

How to compare two Mongodb primitive type Decimal128 in go

问题

如何计算 valueA < valueB?

要比较两个 Decimal128 类型的值 valueA 和 valueB 的大小,可以使用以下方法:

if valueA.LessThan(valueB) {
    // valueA 小于 valueB
} else {
    // valueA 大于等于 valueB
}

在这个例子中,valueA.LessThan(valueB) 方法用于判断 valueA 是否小于 valueB。如果返回 true,则表示 valueA 小于 valueB;如果返回 false,则表示 valueA 大于等于 valueB。

英文:
valueA, _ := primitive.ParseDecimal128(&quot;123.00&quot;)
valueB, _ := primitive.ParseDecimal128(&quot;123.12&quot;)

how to calculate valueA < valueB?

答案1

得分: 3

我找到了一个答案,感谢@Matteo。

有一个函数可以将Decimal128转换为BigInt,并且可以使用BigInt进行比较。

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

	sign := b1.Sign()
	if sign != b2.Sign() {
		if b1.Sign() > 0 {
			return 1, nil
		} else {
			return -1, nil
		}
	}

	if exp1 == exp2 {
		return b1.Cmp(b2), nil
	}

	if sign < 0 {
		if exp1 < exp2 {
			return 1, nil
		}
		return -1, nil
	} else {
		if exp1 < exp2 {
			return -1, nil
		}

		return 1, nil
	}
}

*已编辑指数部分

英文:

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, exp1, err := d1.BigInt()
	if err != nil {
		return 0, err
	}
	b2, exp2, err := d2.BigInt()
	if err != nil {
		return 0, err
	}

	sign := b1.Sign()
	if sign != b2.Sign() {
		if b1.Sign() &gt; 0 {
			return 1, nil
		} else {
			return -1, nil
		}
	}

	if exp1 == exp2 {
		return b1.Cmp(b2), nil
	}

	if sign &lt; 0 {
		if exp1 &lt; exp2 {
			return 1, nil
		}
		return -1, nil
	} else {
		if exp1 &lt; exp2 {
			return -1, nil
		}

		return 1, nil
	}
}

*edited for exponential part

答案2

得分: 1

在这个测试中查找:

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
}

这里

英文:

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
}

huangapple
  • 本文由 发表于 2021年12月24日 14:33:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/70470194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定