Golang 转换字符串变量为双精度浮点数
在本教程中,我们将学习如何在Go编程语言中将字符串变量转换为双精度浮点数。
字符串是一种用于存储字符或字母的数据类型。字符串的大小为1字节或8位。
而双精度浮点数是一种用于存储双精度浮点数的数据类型。双精度浮点数的大小为64位或8字节。
使用ParseFloat()方法将字符串类型变量转换为双精度浮点数的程序
语法
func ParseFloat (s string, bitsize int) (float 64, error)
ParseFloat()函数 用于将字符串转换为浮点数类型的值。该函数接受两个参数,一个是我们希望转换的字符串,另一个是一个整数类型的值。这个值指定了结果的大小。它可以是32位或64位。该函数将最终结果返回为一个64位浮点数类型的数字,以及一个错误,如果在转换过程中出现任何问题,则可以在屏幕上打印出来。如果我们希望以32位浮点数的形式获得结果,则必须将位数指定为32,这使得结果可以转换为32位浮点数。
步骤
- 步骤1 - 导入 fmt、reflect 和 strconv 包。
-
步骤2 - 开始函数 main() 。
-
步骤3 - 声明名为’string’的字符串变量并为其赋值。
-
步骤4 - 使用 reflect.typeof() 函数显示变量的数据类型。
-
步骤5 - 使用 ParseFloat() 方法将字符串转换为双精度。
-
步骤6 - 将转换后的类型存储在一个变量中,并使用 fmt.Println() 函数在屏幕上打印结果。
示例
package main
// import the required packages to perform the task
import (
"fmt"
"reflect"
"strconv"
)
// this is the main function
func main() {
// initialize the srting variable
string := "3.1415926535"
// print the type of variable.
fmt.Println("Type of variable Before conversion is :", reflect.TypeOf(string))
// print the value of string
fmt.Println("String value is: ", string)
// use the ParseFloat() Function on string to convert it into float
x, _ := strconv.ParseFloat(string, 64)
// print the type of variable
fmt.Println("Type of variable After conversion is :", reflect.TypeOf(x))
// print the value of variable
fmt.Println("Float value is: ", x, "\n")
// initialize the srting
string1 := "222.222"
// print the type of variable
fmt.Println("Type of variable Before conversion is :", reflect.TypeOf(string1))
// print the value
fmt.Println("String value is: ", string1)
// use the Parsefloat() Function on string
y, _ := strconv.ParseFloat(string1, 64) //used the bitsize=32, value may vary
// print the type of variable
fmt.Println("Type of variable After conversion is :", reflect.TypeOf(y))
// print the value of variable
fmt.Println("Float value is: ", y, "\n")
}
输出
Type of variable Before conversion is : string
String value is: 3.1415926535
Type of variable After conversion is : float64
Float value is: 3.1415926535
Type of variable Before conversion is : string
String value is: 222.222
Type of variable After conversion is : float64
Float value is: 222.222
代码描述
-
首先,我们导入 fmt、reflect 和 strconv 包。fmt 包用于在屏幕上打印任何内容。reflect 包用于获取变量的当前数据类型。strconv 包用于获取其他预定义函数,如 ParseFloat() 。
-
然后,我们开始 main() 函数来执行任务并将字符串的数据类型转换为 Double 类型。
-
声明并定义一个类型为字符串的变量,并为其赋值。
-
在下一步中,我们使用 strconv 包中定义的 TypeOf() 函数打印刚刚声明的变量的类型。
-
然后,我们使用 fmt.Print() 函数打印数据类型中的实际值。
-
然后,我们从 Go 语言的 “strconv” 包中调用 ParseFloat() 函数,并将字符串传递给该函数以将字符串值转换为 Double 类型。
-
现在,我们已经打印了变量的类型,以检查数据类型是否已从字符串更改为 Double 类型。
-
现在将结果存储在一个单独的变量中,并使用 fmt.Print() 函数将其打印在屏幕上。
结论
我们已经成功编译和执行了将字符串类型变量转换为 Double 类型的 Golang 程序代码。