From 483a047db9d0b74d97661512f7761c63ffc6dbe9 Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 9 Sep 2021 14:03:13 +0300 Subject: [PATCH] Improve performance of Abs() and Round() (#240) --- decimal.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/decimal.go b/decimal.go index 4f6d81a..4e69557 100644 --- a/decimal.go +++ b/decimal.go @@ -457,6 +457,9 @@ func (d Decimal) rescale(exp int32) Decimal { // Abs returns the absolute value of the decimal. func (d Decimal) Abs() Decimal { + if !d.IsNegative() { + return d + } d.ensureInitialized() d2Value := new(big.Int).Abs(d.value) return Decimal{ @@ -879,6 +882,9 @@ func (d Decimal) StringFixedCash(interval uint8) string { // NewFromFloat(545).Round(-1).String() // output: "550" // func (d Decimal) Round(places int32) Decimal { + if d.exp == -places { + return d + } // truncate to places + 1 ret := d.rescale(-places - 1)