go FormatFloat()方法

FormatFloat()方法语法

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

go源码对FormatFloat()方法的介绍:

FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

The format fmt is one of 'b' (-ddddp±ddd, a binary exponent), 'e' (-d.dddde±dd, a decimal exponent), 'E' (-d.ddddE±dd, a decimal exponent), 'f' (-ddd.dddd, no exponent), 'g' ('e' for large exponents, 'f' otherwise), 'G' ('E' for large exponents, 'f' otherwise), 'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or 'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).

The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats. For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point. For 'g' and 'G' it is the maximum number of significant digits (trailing zeros are removed). The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

即,golang的strconv.FormatFloat()方法,可以将一个浮点数float转换为字符串string类型的值,其中各个参数的描述如下表。


参数

参数描述
f指定要转换为string的浮点数
fmt表示格式,其中'b'(-ddddp±ddd,指数为二进制)、'e'(-d.dddde±dd,十进制指数)、'E'(-d.ddddE±dd,十进制指数)、'f' (-ddd.dddd, 无指数的表示方法),'g'(指数很大时用'e'格式,否则'f'格式)、'G'(指数很大时用'E'格式,否则'f'格式)
prec控制精度(排除指数部分):在'f'、'e'、'E'的fmt格式中,prec表示小数点后的数字个数;对'g'、'G'的格式,prec则控制的是总的数字个数。如果prec的值为-1,那么就表示使用最少数量的、且必需的数字来表示f。
bitSize表示第一个参数f的来源类型,其中32表示float32,64则表示float64

strings.TrimPrefix()方法实例代码

func main() {
	var str string = strconv.FormatFloat(0.669, 'E', 2, 64)
	fmt.Println(str)
}

运行go文件,得到输出:

6.69E-01

全栈后端 / go语法 :













Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.