summaryrefslogtreecommitdiff
path: root/round_test.go
blob: 60331565d8614375de57c5139897e48074123ed5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package float

import (
	"fmt"
	"math"
	"testing"
)

func TestRound2(t *testing.T) {
	testCases := []struct {
		in, out float64
	}{
		{0.0, 0.0},
		{0.3, 0.3},
		{0.333, 0.33},
		{0.334, 0.33},
		{0.335, 0.34},
		{-0.333, -0.33},
		{-0.334, -0.33},
		{-0.335, -0.34},
		{495.17999999999995, 495.18},
		{-495.17999999999995, -495.18},
		{0.115, 0.12},
		{-0.115, -0.12},
	}
	for _, tc := range testCases {
		t.Run(fmt.Sprint(tc.in), func(t *testing.T) {
			if r := RoundN(tc.in, 2); r != tc.out {
				t.Errorf("got %v, want %v", r, tc.out)
			}
		})
	}
}

func TestRound(t *testing.T) {
	negZero := math.Copysign(0, -1)
	testCases := []struct {
		in, out float64
	}{
		{-0.49999999999999994, negZero}, // -0.5+epsilon
		{-0.5, -1},
		{-0.5000000000000001, -1}, // -0.5-epsilon
		{0, 0},
		{0.49999999999999994, 0}, // 0.5-epsilon
		{0.5, 1},
		{0.5000000000000001, 1},                         // 0.5+epsilon
		{1.390671161567e-309, 0},                        // denormal
		{2.2517998136852485e+15, 2.251799813685249e+15}, // 1 bit fraction
		{4.503599627370497e+15, 4.503599627370497e+15},  // large integer
		{math.Inf(-1), math.Inf(-1)},
		{math.Inf(1), math.Inf(1)},
		{math.NaN(), math.NaN()},
		{negZero, negZero},
	}
	for _, tc := range testCases {
		t.Run(fmt.Sprint(tc.in, tc.out), func(t *testing.T) {
			r := Round(tc.in)
			if math.Float64bits(r) != math.Float64bits(tc.out) {
				t.Errorf("got %v, want %v", r, tc.out)
			}
		})
	}
}