Integer and float conversion to string and vice versa in Golang

To convert string to Integer value in Golang you need to import strconv library, then call Atoi function as:

 intval, err := strconv.Atoi("123")

to convert string to float call ParseFloat method:

    floatval, err := strconv.ParseFloat("12.1", 0)

To convert Integer to string use Itoa method:

    str := strconv.Itoa(45)

To convert float to string use FormatFloat method:

    str := strconv.FormatFloat(45.124, 'f', 2, 32)

‘f’ is format type, 2 is decimal points, and 32 is bit size

Sprintf method of fmt library could be used instead to return formatted float string:

    str := fmt.Sprintf("%.2f", 45.124)

f is format type (float) and .2 represents two decimal points

Command line flags in Golang

Parameters could be passed to console applications in command line, example:

./MyTool -f /home/user -count 20

In this case parameter flags are: -f, and -count, and parameter values are: /home/user and 20

To apply this in Golang we add “flag” to import and write below code:

func main() {
     folder := flag.String("f""/", 
        "Folder name that contents the files")
     count := flag.Int("count"10"Files number to process")
     flag.Parse()
     fmt.Printf("Selected folder: %s, files count: %d\n", 
         *folder, *count) 
}

Example of usage and output:

./MyTool -f /home -count 20
Selected folder: /home, files count: 20

Calling it with –help:

./MyTool --help
Usage of ./MyTool:
-count int
Files number to process (default 10)
-f string
Folder name that contents the files (default "/")