-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathround.go
77 lines (65 loc) · 1.29 KB
/
round.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
package main
import (
"flag"
"fmt"
"log"
"math/big"
"os"
)
func main() {
log.SetPrefix("round: ")
log.SetFlags(0)
flag.Bool("d", false, "round down")
flag.Usage = usage
flag.Parse()
if flag.NArg() != 2 {
usage()
}
mode := 'u'
flag.Visit(func(f *flag.Flag) {
switch f.Name {
case "d":
mode = 'd'
}
})
target := mknum(flag.Arg(1))
num := mknum(flag.Arg(0))
round(target, num, mode)
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: round [options] number target")
flag.PrintDefaults()
os.Exit(2)
}
func mknum(s string) *big.Int {
n := new(big.Int)
_, ok := n.SetString(s, 0)
if !ok {
log.Fatalf("invalid number %q", s)
}
return n
}
func round(target, num *big.Int, mode rune) {
zero := new(big.Int)
if target.Cmp(zero) == 0 && num.Cmp(zero) == 0 {
fmt.Println("0")
return
}
if num.Cmp(zero) == 0 {
log.Fatalf("number cannot be zero")
}
if target.Cmp(zero) < 0 || num.Cmp(zero) < 0 {
log.Fatalf("target/number cannot be negative")
}
prev := new(big.Int).Set(num)
cur := new(big.Int).Set(num)
for cur.Cmp(target) < 0 {
prev = new(big.Int).Set(num)
cur.Add(cur, num)
}
if mode == 'd' {
fmt.Println("%d | %#x\n", prev, prev)
} else {
fmt.Printf("%d | %#x\n", cur, cur)
}
}