-
Notifications
You must be signed in to change notification settings - Fork 176
/
main.go
45 lines (42 loc) · 836 Bytes
/
main.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
// ex3.11 inserts commas into floating point strings with an optional sign,
// given as command-line arguments.
package main
import (
"bytes"
"fmt"
"os"
"strings"
)
func main() {
for i := 1; i < len(os.Args); i++ {
fmt.Printf("%s\n", comma(os.Args[i]))
}
}
func comma(s string) string {
b := bytes.Buffer{}
mantissaStart := 0
if s[0] == '+' || s[0] == '-' {
b.WriteByte(s[0])
mantissaStart = 1
}
mantissaEnd := strings.Index(s, ".")
if mantissaEnd == -1 {
mantissaEnd = len(s)
}
mantissa := s[mantissaStart:mantissaEnd]
pre := len(mantissa) % 3
if pre > 0 {
b.Write([]byte(mantissa[:pre]))
if len(mantissa) > pre {
b.WriteString(",")
}
}
for i, c := range mantissa[pre:] {
if i%3 == 0 && i != 0 {
b.WriteString(",")
}
b.WriteRune(c)
}
b.WriteString(s[mantissaEnd:])
return b.String()
}