-
Notifications
You must be signed in to change notification settings - Fork 0
/
gofloat.go
71 lines (61 loc) · 1.62 KB
/
gofloat.go
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
64
65
66
67
68
69
70
71
package gofloat
import (
"math"
)
type Float struct {
integer int64
decimal int64
precision int
}
// ToFloat returns a Float of f to given precision
func ToFloat(f float64, precision int) Float {
floatingLength := int64(math.Trunc(math.Pow(10, float64(precision))))
rounded := math.Round(f * float64(floatingLength))
return Float{
integer: int64(rounded) / floatingLength,
decimal: int64(rounded) % floatingLength,
precision: precision,
}
}
// Add returns a Float of f + x
func (f Float) Add(x Float) Float {
max := getMaxPrecision(f.precision, x.precision)
sum := f.Float64() + x.Float64()
return ToFloat(sum, max)
}
// Sub returns a Float of f - x
func (f Float) Sub(x Float) Float {
max := getMaxPrecision(f.precision, x.precision)
sub := f.Float64() - x.Float64()
return ToFloat(sub, max)
}
// Multiply returns a Float of f * x
func (f Float) Multiply(x Float) Float {
max := getMaxPrecision(f.precision, x.precision)
mul := f.Float64() * x.Float64()
return ToFloat(mul, max)
}
// Divide returns a Float of f / x
//
// Special cases are :
// x.Float64 = 0 returns Float value 0
func (f Float) Divide(x Float) Float {
if x.Float64() == 0 {
return ToFloat(0, 0)
}
max := getMaxPrecision(f.precision, x.precision)
dev := f.Float64() / x.Float64()
return ToFloat(dev, max)
}
// Float64 returns a float64 value of f
func (f Float) Float64() float64 {
floatingLength := int64(math.Trunc(math.Pow(10, float64(f.precision))))
return (float64(f.integer*floatingLength) + float64(f.decimal)) / float64(floatingLength)
}
func getMaxPrecision(p1, p2 int) (max int) {
max = p1
if p1 < p2 {
max = p2
}
return
}