-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnumbers.go
716 lines (690 loc) · 18.4 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
// -----------------------------------------------------------------------------
// ZR Library zr/[numbers.go]
// (c) balarabe@protonmail.com License: MIT
// -----------------------------------------------------------------------------
package zr
// # Constants
// MaxInt
// MaxUint
// MinInt
//
// # Regular Expressions
// NumberEx
//
// # Numeric Functions
// Float64(value interface{}) float64
// Float64E(value interface{}) (float64, error)
// Int(value interface{}) int
// IntE(value interface{}) (int, error)
// IsNumber(value interface{}) bool
// MaxIntOf(values []int) (max int, found bool)
// MinMaxGap(values []int) (min, max int)
//
// # Formatting Functions
// BlankZero(s string) string
// CommaDelimit(number string, decimalPlaces int) string
// IntInWordsEN(number int64) string
import (
"bytes"
"errors"
"fmt"
"math"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
)
// -----------------------------------------------------------------------------
// # Constants
const (
// MaxInt _ _
MaxInt = int(MaxUint >> 1)
// MaxUint _ _
MaxUint = ^uint(0)
// MinInt _ _
MinInt = -MaxInt - 1
)
// DigitNamesEN are English names of decimal digits 0 to 9.
// These constants are mainly used by IntInWordsEN().
var DigitNamesEN = []string{
"Zero", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine",
}
// TeensEN are English names of numbers from 11 to 19.
// These constants are mainly used by IntInWordsEN().
var TeensEN = []string{
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen",
}
// TensEN are English names of tens (10, 20,.. 90)
// These constants are mainly used by IntInWordsEN().
var TensEN = []string{
"Ten", "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety",
}
// -----------------------------------------------------------------------------
// # Regular Expressions
// NumberEx is a regular expression that matches positive or negative decimal
// real numbers. A single '-' precedes negative numbers but '+' is not matched
// for positive numbers. A number can contain a single decimal point.
var NumberEx = regexp.MustCompile(`^[-]?\d+[.]?\d*$`)
// -----------------------------------------------------------------------------
// # Numeric Functions
// Float64 converts any simple numeric type or string to float64.
//
// - Dereferences pointers to evaluate the pointed-to type.
// - Converts nil to 0.
// - Converts boolean true to 1, false to 0.
// - Converts numeric strings to float64.
// - Converts strings using strconv.ParseFloat().
// If a string can't be converted, returns 0.
//
// This function can be used in cases where a simple cast won't
// work, and to easily convert interface{} to a float64.
//
// Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as
// strings to avoid bugs from implicit conversion. Use the String method.
//
// If the value can not be converted to float64, returns zero
// and an error. Float64 logs the error (when logging is active).
//
func Float64(value interface{}) float64 {
ret, err := Float64E(value)
if err != nil {
mod.Error(err)
}
return ret
} // Float64
// Float64E converts any simple numeric type or string to float64.
//
// - Dereferences pointers to evaluate the pointed-to type.
// - Converts nil to 0.
// - Converts boolean true to 1, false to 0.
// - Converts numeric strings to float64.
// - Converts strings using strconv.ParseFloat().
// If a string can't be converted, returns 0.
//
// This function can be used in cases where a simple cast won't
// work, and to easily convert interface{} to a float64.
//
// Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as
// strings to avoid bugs from implicit conversion. Use the String method.
//
// If the value can not be converted to float64, returns
// zero and an error. Float64E does not log the error.
//
func Float64E(value interface{}) (float64, error) {
switch v := value.(type) {
case string:
{
ret, err := strconv.ParseFloat(v, 64)
if err != nil {
ret = 0.0
}
return ret, err
}
case int, int64, int32, int16, int8:
{
return float64(reflect.ValueOf(value).Int()), nil
}
case uint, uint64, uint32, uint16, uint8:
{
return float64(reflect.ValueOf(value).Uint()), nil
}
case float64:
{
return v, nil
}
case float32:
{
return float64(v), nil
}
case bool:
{
if v {
return 1.0, nil
}
return 0.0, nil
}
case nil:
{
return 0.0, nil
}
}
// if not converted yet, try to dereference pointer, then convert
xv := reflect.ValueOf(value)
if xv.Kind() == reflect.Ptr {
if xv.IsNil() {
return 0.0, nil
}
ret, err := Float64E(xv.Elem().Interface())
if err == nil {
return ret, nil
}
}
erm := fmt.Sprintf("Can not convert %s to float64: %v",
reflect.TypeOf(value), value)
err := errors.New(erm)
return 0.0, err
} // Float64E
// Int converts any simple numeric type or string to int.
//
// - Dereferences pointers to evaluate the pointed-to type.
// - Converts nil to 0.
// - Converts boolean true to 1, false to 0.
// - Converts numeric strings to int.
// Parsing a string continues until the first non-numeric character.
// Therefore a string like '123AA456' converts to '123'.
//
// This function can be used in cases where a simple cast won't
// work, and to easily convert interface{} to an int.
//
// Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as
// strings to avoid bugs from implicit conversion. Use the String method.
//
// If the value can not be converted to int, returns
// zero and logs an error (when logging is active).
//
func Int(value interface{}) int {
ret, err := IntE(value)
if err != nil {
mod.Error(err)
}
return ret
} // Int
// IntE converts any simple numeric type or string to int.
//
// - Dereferences pointers to evaluate the pointed-to type.
// - Converts nil to 0.
// - Converts boolean true to 1, false to 0.
// - Converts numeric strings to int.
// Parsing a string continues until the first non-numeric character.
// Therefore a string like '123AA456' converts to '123'.
// while a non-numeric string converts to 0.
//
// This function can be used in cases where a simple cast won't
// work, and to easily convert interface{} to an int.
//
// Note: fmt.Stringer (or fmt.GoStringer) interfaces are not treated as
// strings to avoid bugs from implicit conversion. Use the String method.
//
// If the value can not be converted to int, returns
// zero and an error. IntE does not log the error.
//
func IntE(value interface{}) (int, error) {
switch v := value.(type) {
case string:
{
n := 0
var hasDigit, hasMinus, hasPlus bool
loop:
for _, ch := range v {
//
// ignore leading spaces
if !(hasDigit || hasMinus || hasPlus) {
for _, sp := range SPACES {
if ch == sp {
continue loop
}
}
}
// handle '-' and '+' signs
if ch == '-' || ch == '+' {
if hasMinus || hasPlus || hasDigit {
return n, nil
}
if ch == '-' {
hasMinus = true
} else {
hasPlus = true
}
continue loop
}
// add digits to result
if ch >= '0' && ch <= '9' {
hasDigit = true
n = n*10 + int(ch-'0')
continue loop
}
break
}
if hasMinus {
n = -n
}
return n, nil
}
case int:
{
return v, nil
}
case int64, int32, int16, int8:
{
return int(reflect.ValueOf(value).Int()), nil
}
case float64, float32:
{
n := reflect.ValueOf(value).Float()
if n < -float64(math.MinInt64) || n > float64(math.MaxInt64) {
err := errors.New(EOverflow)
if n < 0 {
return math.MinInt32, err
}
return math.MaxInt32, err
}
return int(n), nil
}
case uint, uint64, uint32, uint16, uint8:
{
return int(reflect.ValueOf(value).Uint()), nil
}
case bool:
{
if v {
return 1, nil
}
return 0, nil
}
case nil:
{
return 0, nil
}
}
// if not converted yet, try to dereference pointer, then convert
v := reflect.ValueOf(value)
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return 0, nil
}
ret, err := IntE(v.Elem().Interface())
if err == nil {
return ret, nil
}
}
erm := fmt.Sprintf("Can not convert %s to int: %v",
reflect.TypeOf(value), value)
err := errors.New(erm)
return 0, err
} // IntE
// IsNumber returns true if value is a number or numeric string,
// or false otherwise. It also accepts pointers to numeric types
// and strings. Always returns false if value is nil or bool,
// even though Int() can convert bool to 1 or 0.
func IsNumber(value interface{}) bool {
const (
groupSeparatorChar = ','
decimalPointChar = '.'
)
switch v := value.(type) {
case int, int64, int32, int16, int8, float64, float32,
uint, uint64, uint32, uint16, uint8,
*int, *int64, *int32, *int16, *int8, *float64, *float32,
*uint, *uint64, *uint32, *uint16, *uint8:
{
return true
}
case string:
{
s := strings.TrimSpace(v)
if len(s) < 1 {
return false
}
var hasDecPoint, hasDigit, hasSign, prevSep bool
for _, r := range s {
switch {
case r >= '0' && r <= '9':
{
hasDigit = true
}
case r == groupSeparatorChar:
{
// two consecutive group separators
// make string non-numeric
if prevSep || !hasDigit {
return false
}
prevSep = true
continue
}
case r == '-' || r == '+':
{
if hasSign || hasDigit {
return false
}
hasSign = true
}
case r == decimalPointChar:
{
if hasDecPoint {
return false
}
hasDecPoint = true
}
default:
return false
}
prevSep = false
}
return hasDigit
}
case *string:
if v != nil {
return IsNumber(*v)
}
}
return false
} // IsNumber
// MinMaxGap returns the lowest and highest unique integer that can
// fit in a gap in a series of integers. E.g. given 1, 4, and 7
// this would be 2 and 6. Returns the resulting integers if there
// is a gap, or MaxInt and MinInt if there is no gap in the series.
func MinMaxGap(values []int) (min, max int) {
//
// return immediately when the slice has less than 2 values:
if len(values) < 2 {
return MaxInt, MinInt
}
// copy and sort the input slice, so original is unchanged
ar := make([]int, len(values))
copy(ar, values)
sort.Ints(ar)
//
// find the lowest unused integer in range
min = MaxInt
for i := 0; i < len(ar)-1; i++ {
if ar[i+1] != ar[i] && ar[i+1] != ar[i]+1 {
min = ar[i] + 1
break
}
}
// find the highest unused integer in range
max = MinInt
for i := len(ar) - 1; i > 0; i-- {
if ar[i-1] != ar[i] && ar[i-1] != ar[i]-1 {
max = ar[i] - 1
break
}
}
return min, max
} // MinMaxGap
// MaxIntOf returns the maximum value in a slice of integers (and true
// in the second returned value) or 0 and false if the slice is empty.
func MaxIntOf(values []int) (max int, found bool) {
if len(values) == 0 {
return 0, false
}
for _, n := range values {
if n > max || !found {
max = n
found = true
}
}
return max, found
} // MaxIntOf
// -----------------------------------------------------------------------------
// # Formatting Functions
// AmountInWordsEN returns the currency value as an English description in words
// This function is useful for showing amounts in invoices, etc.
//
// Uses English language names, hence the 'EN' suffix.
//
// fmt: a string specifying the currency format:
// format_ = "<Large-Single>;<Large-Plural>;<S-Single>;<S-Plural>;<Only>"
// Large-Single - Large Denomination, Singular. E.g. "Dollar"
// Large-Plural - Large Denomination, Plural. E.g. "Dollars"
// S-Single - Small Denomination, Singular. E.g. "Cent"
// S-Plural - Small Denomination, Plural. E.g. "Cents"
//
// All the format specifiers are optional but must follow in
// the order specified. If a plural specifier is omitted, then
// an "s" is added to the singular specifier for values greater
// than 1. If the singular specifier is omitted, Then the
// plural is used for all values (Used for some currencies).
// If both specifiers are omitted for either denomination, the
// denomination will not be returned. See the examples below.
//
// Returns: The amount in words as a string, including the currency
// and the word "Only". Uses proper capitalisation.
//
// Example: PARAMETER RESULT
// (11.02,";;Cent;Only") "Two Cents Only"
// (11.02,"Dollar;;Cent") "Eleven Dollars and Two Cents"
// (11.02,"Euro") "Eleven Euros"
// (11.02,"Pound;;;Pence") "Eleven Pounds and Two Pence"
func AmountInWordsEN(n Currency, fmt string) string {
i := n.i64
if i < 0 {
i = -n.i64
}
var (
bigUnits = i / 1e4
smlUnits = (i - bigUnits*1e4) / 100
hasOnly = strings.HasSuffix(strings.ToLower(fmt), "only")
)
if hasOnly {
fmt = fmt[:len(fmt)-4]
}
getPart := func(partNo int) string {
parts := strings.Split(fmt, ";")
if partNo < 0 || partNo >= len(parts) {
return ""
}
return parts[partNo]
}
var (
big1 = getPart(0)
bigN = getPart(1)
sml1 = getPart(2)
smlN = getPart(3)
ret = ""
)
if bigUnits > 0 && (big1+bigN) != "" {
ret += IntInWordsEN(bigUnits) + " "
if big1 == "" && bigN != "" {
ret += bigN
} else if big1 != "" && bigN == "" {
ret += big1
if bigUnits > 1 {
ret += "s"
}
} else if big1 != "" && bigN != "" {
if bigUnits == 1 {
ret += big1
}
if bigUnits > 1 {
ret += bigN
}
}
}
if ((sml1 + smlN) != "") && smlUnits > 0 {
if (big1+bigN != "") && bigUnits > 0 {
ret += " and "
}
ret += IntInWordsEN(smlUnits) + " "
if sml1 == "" && smlN != "" {
ret += smlN
} else if sml1 != "" && smlN == "" {
ret += sml1
if smlUnits > 1 {
ret += "s"
}
} else if sml1 != "" && smlN != "" {
if smlUnits == 1 {
ret += sml1
}
if smlUnits > 1 {
ret += smlN
}
}
}
if hasOnly && len(strings.TrimSpace(ret)) > 0 {
ret += " Only"
}
return ret
} // AmountInWordsEN
// BlankZero returns a blank string when given a string
// containing only zeros, decimal points and white-spaces.
// Any string that doesn't contain '0' is returned unchanged.
func BlankZero(s string) string {
if !strings.Contains(s, "0") {
return s
}
for _, ch := range s {
if ch != ' ' && ch != '.' &&
ch != '\a' && ch != '\b' &&
ch != '\f' && ch != '\n' &&
ch != '\r' && ch != '\t' &&
ch != '\v' && ch != '0' {
return s
}
}
return ""
} // BlankZero
// TODO: CommaDelimit should accept interface{} in number
// CommaDelimit delimits a numeric string with commas (grouped every
// three digits) and also sets the required number of decimal places.
// Numbers are not rounded, just cut at the required number of decimals.
func CommaDelimit(number string, decimalPlaces int) string {
var (
buf = bytes.NewBuffer(make([]byte, 0, 32))
ws = buf.WriteString
intLen = 0
decAt = strings.Index(number, ".")
)
// calculate length of number's integer part
if decAt == -1 {
intLen = len(number)
} else if decAt != 0 {
intLen = decAt
}
{ // write delimited integer part
var (
groups = (intLen / 3) + 1
digits = intLen % 3
at = 0
)
for groups > 0 {
ws(number[at : at+digits])
if groups > 1 && digits != 0 {
ws(",")
}
at += digits
digits = 3
groups--
}
}
if intLen == 0 {
ws("0")
}
if decimalPlaces > 0 { // write fractional part
ws(".")
decLen := 0
if decAt != -1 {
decLen = len(number[decAt+1:])
}
if decLen > decimalPlaces {
decLen = decimalPlaces
}
if decLen > 0 {
ws(number[decAt+1 : decAt+1+decLen])
}
for decLen < decimalPlaces {
ws("0")
decLen++
}
}
// TODO: fix "-," in code above, so this patch wont be needed:
ret := buf.String()
if strings.Contains(ret, "-,") {
ret = strings.Replace(ret, "-,", "-", 1)
}
return ret
} // CommaDelimit
// IntInWordsEN returns the given number as a description in words.
// Uses English language names, hence the 'EN' suffix.
// This function is useful for showing amounts in invoices, etc.
// 'number' must be a positive integer in the range of 0 to 1 trillion.
// E.g. IntInWordsEN(256) returns "Two Hundred and Fifty Six"
func IntInWordsEN(number int64) string {
if number == 0 {
return DigitNamesEN[0]
}
// divide number into billions, millions, thousands, units, etc.
groups := []struct {
n int64
unit string
base int64
}{
{0, "", 1}, // units
{0, "Thousand", 1e3}, // 10^3 (10^3 has 3 zeros, etc)
{0, "Million", 1e6}, // 10^6
{0, "Billion", 1e9}, // 10^9
{0, "Trillion", 1e12}, // 10^12
{0, "Quadrillion", 1e15}, // 10^15
{0, "Quintillion", 1e18}, // 10^18
// math.MaxInt64 = 9223372036854775807
}
{
n := number
for i := len(groups) - 1; i >= 0; i-- {
gr := &groups[i]
if n < gr.base {
continue
}
gr.n = n / gr.base
n -= gr.n * gr.base
}
}
var retBuf bytes.Buffer
ws := retBuf.WriteString
for i := len(groups) - 1; i >= 0; i-- {
n := groups[i].n
if n == 0 {
continue
}
unit := groups[i].unit
//
// count hundreds, tens and units
n100 := n / 100
n -= n100 * 100
n10 := n / 10
n -= n10 * 10
n1 := n
//
// append names of hundreds to result
if n100 != 0 {
ws(" ")
ws(DigitNamesEN[n100])
ws(" Hundred")
}
if (n1 != 0 || n10 != 0) && n100 != 0 {
ws(" and")
}
// append tens and units (or teen numbers) to result
switch {
case n10 == 1 && n1 != 0:
if n1 >= 0 && n1 <= 9 {
ws(" ")
ws(TeensEN[n1-1])
}
case n10 == 0 && n1 != 0:
{
ws(" ")
ws(DigitNamesEN[n1])
}
default:
if n10 != 0 {
ws(" ")
ws(TensEN[n10-1])
}
if n1 != 0 {
ws(" ")
ws(DigitNamesEN[n1])
}
}
ws(" ")
ws(unit)
}
return strings.TrimSpace(retBuf.String())
} // IntInWordsEN
// end