Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,21 @@
return newDecimal(false, d.coef, d.prec)
}

// CopySign returns a value with the magnitude of d and the sign of sign.
//
// Examples:
//
// CopySign(10, 2) = 10
// CopySign(10, -3) = -10
// CopySign(-10, 2) = 10
// CopySign(-10, -3) = -10
func (d Decimal) CopySign(sign Decimal) Decimal {
if d.neg == sign.neg {
return d
}
return d.Neg()
}

// Sign returns:
//
// -1 if d < 0
Expand Down Expand Up @@ -1685,7 +1700,7 @@
return Decimal{}, errOverflow
}

//nolint:gosec // 0 <= coef.bitLen() < 256, so it's safe to convert to uint

Check failure on line 1703 in decimal.go

View workflow job for this annotation

GitHub Actions / lint

directive `//nolint:gosec // 0 <= coef.bitLen() < 256, so it's safe to convert to uint` is unused for linter "gosec" (nolintlint)
bitLen := uint(coef.bitLen())

// initial guess = 2^((bitLen + 1) / 2) ≥ √coef
Expand Down
27 changes: 27 additions & 0 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1671,6 +1671,33 @@ func TestSign(t *testing.T) {
}
}

func TestCopySign(t *testing.T) {
testcases := []struct {
a string
sign string
want string
}{
{"+0", "1", "0"},
{"0", "1", "0"},
{"0", "-1", "0"},
{"-0", "-1", "0"},
{"10", "2", "10"},
{"10", "-3", "-10"},
{"-10", "2", "10"},
{"-10", "-3", "-10"},
}

for _, tc := range testcases {
t.Run(tc.a+"/"+tc.sign, func(t *testing.T) {
a := MustParse(tc.a)
sign := MustParse(tc.sign)
want := MustParse(tc.want)

require.Equal(t, want, a.CopySign(sign))
})
}
}

func TestRoundBank(t *testing.T) {
testcases := []struct {
a string
Expand Down
Loading