将输入整数按照格式分割输出

2021-07-06  本文已影响0人  sjyu_eadd

示例:
输入:1234
输出:1,234

输入:211111234
输出:211,111,234

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    inputReader := bufio.NewReader(os.Stdin)
    fmt.Printf("Please input:")
    input, err := inputReader.ReadString('\n')
    if err != nil {
        fmt.Println("There were errors reading, exiting program.")
        return
    }
    fmt.Println("Your input is:", input)
    input1, err := strconv.Atoi(strings.Replace(input, "\r\n", "", -1))
    if err != nil {
        fmt.Println("strconv.Atoi error, exiting program.")
        return
    }
    var result string
    for input1 > 0 {
        if input1 / 1000 == 0 {
            result = strconv.Itoa(input1 % 1000) + result
        } else {
            result = "," + strconv.Itoa(input1 % 1000) + result
        }
        input1 /= 1000
    }
    fmt.Println("convert result:", result)
}
上一篇下一篇

猜你喜欢

热点阅读