golang int 转float 强转和高精度转操作
时间:2021-04-23 09:30:45|栏目:Golang|点击: 次
golang int 转float
方法一:
强转:
代码如下:
import "fmt" func main() { var money int money = 1 fmt.Println(float64(money) / float64(100)) }
输出结果:0.01
方法二:
高精度转:
代码如下:
import ( "fmt" "math/big" "strconv" ) func main() { totalAmount := 1 numrator, _ := new(big.Float).SetPrec(uint(1024)).SetString(strconv.Itoa(totalAmount)) denominator := big.NewFloat(100) denominator1 := numrator.Quo(numrator, denominator) fmt.Println(denominator1) }
输出结果:0.01
补充:golang float32/64与[]byte互转
网络协议开发中经常需要将int、float、bool等转为二进制数据,float32、64 与[]byte处理:
import ( "encoding/binary" "math" ) func Float32ToByte(float float32) []byte { bits := math.Float32bits(float) bytes := make([]byte, 4) binary.LittleEndian.PutUint32(bytes, bits) return bytes } func ByteToFloat32(bytes []byte) float32 { bits := binary.LittleEndian.Uint32(bytes) return math.Float32frombits(bits) } func Float64ToByte(float float64) []byte { bits := math.Float64bits(float) bytes := make([]byte, 8) binary.LittleEndian.PutUint64(bytes, bits) return bytes } func ByteToFloat64(bytes []byte) float64 { bits := binary.LittleEndian.Uint64(bytes) return math.Float64frombits(bits) }
上一篇:golang切片反序实例
栏 目:Golang
下一篇:Goland 的安装及激活教程(window、linux下安装)
本文标题:golang int 转float 强转和高精度转操作
本文地址:http://www.codeinn.net/misctech/107356.html