Golang程序 将字符串变量转换为double
在本教程中,我们将学习如何在Go编程语言中把字符串变量转换为double。
字符串是一种数据类型,用于存储字符或字母。字符串的大小为1字节或8位。
而double是一种用于存储双精度浮点数的数据类型。double的大小是64位或8字节。
使用ParseFloat()方法将字符串类型的变量转换成double的程序
语法
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() 方法将字符串转换为Double。
-
第5步 – 将转换后的类型存储在一个变量中,并使用 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()函数将其打印在屏幕上。
总结
我们已经成功地编译并执行了Golang程序代码,使用函数将字符串类型的变量转换为Double。