gitee.com/quant1x/num@v0.3.2/decimals_test.go (about) 1 package num 2 3 import ( 4 _ "cmp" 5 "fmt" 6 "math" 7 "testing" 8 ) 9 10 func roundFloat(val float64, precision uint) float64 { 11 ratio := math.Pow(10, float64(precision)) 12 return math.Round(val*ratio) / ratio 13 } 14 15 func TestRound(t *testing.T) { 16 number := 12.3456789 17 fmt.Println(roundFloat(number, 2)) 18 fmt.Println(roundFloat(number, 3)) 19 fmt.Println(roundFloat(number, 4)) 20 fmt.Println(roundFloat(number, 5)) 21 number = -12.3456789 22 fmt.Println(roundFloat(number, 0)) 23 fmt.Println(roundFloat(number, 1)) 24 fmt.Println(roundFloat(number, 3)) 25 26 fmt.Println("fix:", Decimal(number, 3)) 27 fmt.Printf("%f\n", 9.825) 28 } 29 30 func TestDecimal0(t *testing.T) { 31 f := -0.116 32 fmt.Println(math.Signbit(f)) 33 fmt.Println(f) 34 fmt.Printf("%.2f\n", f) 35 } 36 37 func TestDecimal(t *testing.T) { 38 type args struct { 39 value float64 40 digits []int 41 } 42 tests := []struct { 43 name string 44 args args 45 want float64 46 }{ 47 { 48 name: "T9.8", 49 args: args{ 50 value: 9.825, 51 digits: []int{0}, 52 }, 53 want: 10, 54 }, 55 { 56 name: "T9.825", 57 args: args{ 58 value: 9.825, 59 digits: []int{2}, 60 }, 61 want: 9.83, 62 }, 63 { 64 name: "T0.116", 65 args: args{ 66 value: 0.116, 67 digits: []int{2}, 68 }, 69 want: 0.12, 70 }, 71 { 72 name: "T0.11", 73 args: args{ 74 value: 0.1115355659035776, 75 digits: []int{2}, 76 }, 77 want: 0.11, 78 }, 79 { 80 name: "T-0.11", 81 args: args{ 82 value: -0.1115355659035776, 83 digits: []int{2}, 84 }, 85 want: -0.11, 86 }, 87 } 88 for _, tt := range tests { 89 t.Run(tt.name, func(t *testing.T) { 90 if got := Decimal(tt.args.value, tt.args.digits...); got != tt.want { 91 t.Errorf("Decimal() = %v, want %v", got, tt.want) 92 } 93 }) 94 } 95 }