gopl-zh.github.com/vendor/gopl.io/ch3/comma/main.go
github-actions[bot] ca571eb691 deploy: 06a1bdf735
2022-08-04 06:59:33 +00:00

41 lines
680 B
Go

// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 73.
// Comma prints its argument numbers with a comma at each power of 1000.
//
// Example:
// $ go build gopl.io/ch3/comma
// $ ./comma 1 12 123 1234 1234567890
// 1
// 12
// 123
// 1,234
// 1,234,567,890
//
package main
import (
"fmt"
"os"
)
func main() {
for i := 1; i < len(os.Args); i++ {
fmt.Printf(" %s\n", comma(os.Args[i]))
}
}
//!+
// comma inserts commas in a non-negative decimal integer string.
func comma(s string) string {
n := len(s)
if n <= 3 {
return s
}
return comma(s[:n-3]) + "," + s[n-3:]
}
//!-