-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumbers.go
118 lines (99 loc) · 2.09 KB
/
numbers.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// gotools is set of simple math and test helpers.
//
// ## Install
// go get github.com/DeyV/gotools
package gotools
import (
"math"
"strconv"
)
// NumberFormat convert float or int to string (like PHP number_format() )
// in local format, for example:
// NumberFormat( 123456.12, 4, ",", " " )
// >> 123 456,1200
//
// Special cases are:
// NumberFormat(±Inf) = formatted 0.0
// NumberFormat(NaN) = formatted 0.0
func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string {
if math.IsNaN(number) || math.IsInf(number, 0) {
number = 0
}
var ret string
var negative bool
if number < 0 {
number *= -1
negative = true
}
d, fract := math.Modf(number)
if decimals <= 0 {
fract = 0
} else {
pow := math.Pow(10, float64(decimals))
fract = RoundPrec(fract*pow, 0)
}
if thousandsSep == "" {
ret = strconv.FormatFloat(d, 'f', 0, 64)
} else if d >= 1 {
var x float64
for d >= 1 {
d, x = math.Modf(d / 1000)
x = x * 1000
ret = strconv.FormatFloat(x, 'f', 0, 64) + ret
if d >= 1 {
ret = thousandsSep + ret
}
}
} else {
ret = "0"
}
fracts := strconv.FormatFloat(fract, 'f', 0, 64)
// "0" pad left
for i := len(fracts); i < decimals; i++ {
fracts = "0" + fracts
}
ret += decPoint + fracts
if negative {
ret = "-" + ret
}
return ret
}
// Round convert x to int with correct math round
//
// Special cases are:
// Round(±0) = ±0
// Round(±Inf) = ±0
// Round(NaN) = 0
func Round(x float64) int {
if math.IsNaN(x) || math.IsInf(x, 0) {
return 0
}
val := RoundPrec(x, 0)
return int(val)
}
// RoundPrec return rounded version of x with prec precision.
//
// Special cases are:
// Round(±0) = ±0
// Round(±Inf) = ±Inf
// Round(NaN) = NaN
func RoundPrec(x float64, prec int) float64 {
if math.IsNaN(x) || math.IsInf(x, 0) {
return x
}
sign := 1.0
if x < 0 {
sign = -1
x *= -1
}
var rounder float64
pow := math.Pow(10, float64(prec))
intermed := x * pow
_, frac := math.Modf(intermed)
if frac >= 0.5 {
rounder = math.Ceil(intermed)
} else {
rounder = math.Floor(intermed)
}
return rounder / pow * sign
}