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 33 34 35 36 37 38 39 40 41 42 43 44 45
| // FormatFloat 将浮点数 f 转换为字符串值 // f:要转换的浮点数 // fmt:格式标记(b、e、E、f、g、G) // prec:精度(数字部分的长度,不包括指数部分) // bitSize:指定浮点类型(32:float32、64:float64) // // 格式标记: // 'b' (-ddddp±ddd,二进制指数) // 'e' (-d.dddde±dd,十进制指数) // 'E' (-d.ddddE±dd,十进制指数) // 'f' (-ddd.dddd,没有指数) // 'g' ('e':大指数,'f':其它情况) // 'G' ('E':大指数,'f':其它情况) // // 如果格式标记为 'e','E'和'f',则 prec 表示小数点后的数字位数 // 如果格式标记为 'g','G',则 prec 表示总的数字位数(整数部分+小数部分) func FormatFloat(f float64, fmt byte, prec, bitSize int) string
func main() { f := 100.12345678901234567890123456789 fmt.Println(strconv.FormatFloat(f, 'b', 5, 32)) // 13123382p-17 fmt.Println(strconv.FormatFloat(f, 'e', 5, 32)) // 1.00123e+02 fmt.Println(strconv.FormatFloat(f, 'E', 5, 32)) // 1.00123E+02 fmt.Println(strconv.FormatFloat(f, 'f', 5, 32)) // 100.12346 fmt.Println(strconv.FormatFloat(f, 'g', 5, 32)) // 100.12 fmt.Println(strconv.FormatFloat(f, 'G', 5, 32)) // 100.12 fmt.Println(strconv.FormatFloat(f, 'b', 30, 32)) // 13123382p-17 fmt.Println(strconv.FormatFloat(f, 'e', 30, 32)) // 1.001234588623046875000000000000e+02 fmt.Println(strconv.FormatFloat(f, 'E', 30, 32)) // 1.001234588623046875000000000000E+02 fmt.Println(strconv.FormatFloat(f, 'f', 30, 32)) // 100.123458862304687500000000000000 fmt.Println(strconv.FormatFloat(f, 'g', 30, 32)) // 100.1234588623046875 fmt.Println(strconv.FormatFloat(f, 'G', 30, 32)) // 100.1234588623046875 }
|