SoFunction
Updated on 2025-03-05

golang string, int, int64 float Converting method

golang string, int, int64 float converts each other

#string to intint,err := (string)  
#string to int64int64, err := (string, 10, 64)  
//The second parameter is the cardinality (2~36),//The third parameter bit size represents the result type of the expected conversion, and its values ​​can be 0, 8, 16, 32 and 64,// Corresponding to int, int8, int16, int32 and int64 respectively#int to stringstring := (int) 
//Equivalent tostring := (int64(int),10)
#int64 to stringstring := (int64,10)  
//The second parameter is the cardinality, 2~36 can be selected//For unsigned integers, you can use Format Uint(i int64, base int)#float to stringstring := (float32,'E',-1,32)
string := (float64,'E',-1,64)
// 'b' (-ddddp±ddd, binary index)// 'e' (-±dd, decimal index)// 'E' (-±dd, decimal index)// 'f' (-, no index)// 'g' ('e':big index, 'f': other situations)// 'G' ('E':Big Index, 'f':Other Situation)#string to float64float,err := (string,64)
#string to float32float,err := (string,32)
#int to int64int64_ := int64(1234)

golang float string int Convert each other retains decimal places

string to float

package main
import (
    "fmt"
    "strconv"
)
func main() {
    input := "3.14"
    f_input, _ := (input, 64)
    ("%f - %T", f_input, f_input)
}

Execution results

> go run
3.140000 - float64

int converts to float

score := 100
f_score := float64(score)
("%f - %T\n", f_score, f_score)
> 100.000000 - float64

Convert to string and keep 3 decimal places

s_score := ("%.3f", f_score)

Note that retaining 3 decimal places will automatically round.

Whether it is a 32-bit system or a 64-bit system, float64 is supported

ubuntu check whether the system is 32-bit or 64-bit

> uname -a
Linux 509B65C8YW2THMJ 4.4.0-18362-Microsoft #1-Microsoft Mon Mar 18 12:02:00 PST 2019 x86_64 x86_64 x86_64 GNU/Linux

Because 32 bits are just the number of bits processed by the register at one time. With different algorithms, no matter how big the number is, it can be processed.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.