Golang float 与 string,int 类型的相互转换,及如何保留小数位

发布时间: 2019-11-04 17:48:11 作者: 大象笔记

今天在用 Golang 实现涨幅计算器的时候,第一次接触 Golang 的 float 类型。

这里记录一些 float 类型的基本转换操作。

string 转换为 float

package main

import (
	"fmt"
	"strconv"
)

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

执行结果

> go run main.go
3.140000 - float64

int 转化为 float

score := 100
f_score := float64(score)
fmt.Printf("%f - %T\n", f_score, f_score)

> 100.000000 - float64

转换为 string,并保留3位小数

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

注意,这样保留3位小数会自动四舍五入。

无论是 32位系统还是 64 位系统,都支持 float64

ubuntu 查看系统是 32 位还是 64 位

> 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

因为32位只是寄存器的一次处理的位数。配合不同的算法,多大的数字都可以处理。

我是一名山东烟台的开发者,联系作者