Blame view

float_util.go 1.29 KB
b80ee4b2b   Marko Tikvić   new stuff
1
2
3
4
5
6
  package webutility
  
  import (
  	"fmt"
  	"math"
  	"math/big"
bf3ea2f8e   Marko Tikvić   format number
7
  	"strings"
b80ee4b2b   Marko Tikvić   new stuff
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
  )
  
  func RoundFloat64(f float64, dec int) float64 {
  	p := math.Pow(10, float64(dec))
  	return math.Round(f*p) / p
  }
  
  func NewBF(f float64, prec uint) *big.Float {
  	x := big.NewFloat(f)
  	x.SetPrec(prec)
  	return x
  }
  
  func AddBF(x, y *big.Float) *big.Float {
  	z := big.NewFloat(0.0)
  	z.SetPrec(x.Prec())
  	z.Add(x, y)
  	return z
  }
  
  func SubBF(x, y *big.Float) *big.Float {
  	z := big.NewFloat(0.0)
  	z.SetPrec(x.Prec())
  
  	yneg := big.NewFloat(0.0)
  	yneg.Neg(y)
  
  	z.Add(x, yneg)
  	return z
  }
  
  func MulBF(x, y *big.Float) *big.Float {
  	z := big.NewFloat(0.0)
  	z.SetPrec(x.Prec())
  	z.Mul(x, y)
  	return z
  }
  
  func DivBF(x, y *big.Float) *big.Float {
  	z := big.NewFloat(0.0)
  	z.SetPrec(x.Prec())
  	z.Quo(x, y)
  	return z
  }
  
  func BFtoFloat(f *big.Float) float64 {
  	v, _ := f.Float64()
  	return v
  }
  
  func Float64ToString(f float64) string {
  	return fmt.Sprintf("%.2f", f)
  }
1b51eed04   Marko Tikvić   pdf helper
61
62
63
64
65
66
67
  
  func Float64PtrToString(f *float64) string {
  	if f == nil {
  		return ""
  	}
  	return fmt.Sprintf("%.2f", *f)
  }
bf3ea2f8e   Marko Tikvić   format number
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
  
  func FormatFloat64Number(f float64, dec int) string {
  	res := ""
  
  	f = RoundFloat64(f, dec)
  
  	i := int64(f)
  
  	format := fmt.Sprintf("%%.%df", dec)
  	parts := strings.Split(fmt.Sprintf(format, f-float64(i)), ".")
  
  	decimals := parts[1]
  
  	res = FormatInt64Number(i) + "," + decimals
  
  	return res
  }