golang int to float
Method 1:
Strong turn:
The code is as follows:
import "fmt" func main() { var money int money = 1 (float64(money) / float64(100)) }
Output result: 0.01
Method 2:
High precision rotation:
The code is as follows:
import ( "fmt" "math/big" "strconv" ) func main() { totalAmount := 1 numrator, _ := new().SetPrec(uint(1024)).SetString((totalAmount)) denominator := (100) denominator1 := (numrator, denominator) (denominator1) }
Output result: 0.01
Supplement: golang float32/64 and []byte are transferred
In network protocol development, int, float, bool, etc. often need to be converted into binary data, and float32, 64 and []byte are processed:
import ( "encoding/binary" "math" ) func Float32ToByte(float float32) []byte { bits := math.Float32bits(float) bytes := make([]byte, 4) .PutUint32(bytes, bits) return bytes } func ByteToFloat32(bytes []byte) float32 { bits := .Uint32(bytes) return math.Float32frombits(bits) } func Float64ToByte(float float64) []byte { bits := math.Float64bits(float) bytes := make([]byte, 8) .PutUint64(bytes, bits) return bytes } func ByteToFloat64(bytes []byte) float64 { bits := .Uint64(bytes) return math.Float64frombits(bits) }
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.