MCPcopy
hub / github.com/shopspring/decimal / TestDecimal_DivRound

Function TestDecimal_DivRound

decimal_test.go:2064–2101  ·  view source on GitHub ↗

rules for rounded divide, rounded to integer rounded_divide(d,d2) = q sign q * sign (d/d2) >= 0 for d and d2 >0 : q is already rounded q = d/d2 + r , with r > -0.5 and r <= 0.5 thus q-d/d2 = r, with r > -0.5 and r <= 0.5 and d2 q -d = r d2 with r d2 > -d2/2 and r d2 <= d2/2 and 2 (d2 q -d) = x with

(t *testing.T)

Source from the content-addressed store, hash-verified

2062// if we factor in precision then x > -d2 * 10^(-precision) and x <= d2 * 10(-precision)
2063
2064func TestDecimal_DivRound(t *testing.T) {
2065 cases := []struct {
2066 d string
2067 d2 string
2068 prec int32
2069 result string
2070 }{
2071 {"2", "2", 0, "1"},
2072 {"1", "2", 0, "1"},
2073 {"-1", "2", 0, "-1"},
2074 {"-1", "-2", 0, "1"},
2075 {"1", "-2", 0, "-1"},
2076 {"1", "-20", 1, "-0.1"},
2077 {"1", "-20", 2, "-0.05"},
2078 {"1", "20.0000000000000000001", 1, "0"},
2079 {"1", "19.9999999999999999999", 1, "0.1"},
2080 }
2081 for _, s := range cases {
2082 d, _ := NewFromString(s.d)
2083 d2, _ := NewFromString(s.d2)
2084 result, _ := NewFromString(s.result)
2085 prec := s.prec
2086 q := d.DivRound(d2, prec)
2087 if sign(q)*sign(d)*sign(d2) < 0 {
2088 t.Errorf("sign of quotient wrong, got: %v/%v is about %v", d, d2, q)
2089 }
2090 x := q.Mul(d2).Abs().Sub(d.Abs()).Mul(New(2, 0))
2091 if x.Cmp(d2.Abs().Mul(New(1, -prec))) > 0 {
2092 t.Errorf("wrong rounding, got: %v/%v prec=%d is about %v", d, d2, prec, q)
2093 }
2094 if x.Cmp(d2.Abs().Mul(New(-1, -prec))) <= 0 {
2095 t.Errorf("wrong rounding, got: %v/%v prec=%d is about %v", d, d2, prec, q)
2096 }
2097 if !q.Equal(result) {
2098 t.Errorf("rounded division wrong %s / %s scale %d = %s, got %v", s.d, s.d2, prec, s.result, q)
2099 }
2100 }
2101}
2102
2103func TestDecimal_DivRound2(t *testing.T) {
2104 for _, tc := range createDivTestCases() {

Callers

nothing calls this directly

Calls 9

NewFromStringFunction · 0.85
signFunction · 0.85
NewFunction · 0.85
DivRoundMethod · 0.80
MulMethod · 0.80
SubMethod · 0.80
AbsMethod · 0.80
CmpMethod · 0.80
EqualMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…