方法一:
强转:
代码如下:
1
2
3
4
5
6
|
import "fmt" func main() { var money int money = 1 fmt.Println(float64(money) / float64(100)) } |
输出结果:0.01
方法二:
高精度转:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
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处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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) } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/weixin_45604257/article/details/104925267