Go语言程序:将字符串变量转换为双精度浮点数
在本教程中,我们将学习如何在 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() 方法将字符串转换为双精度浮点数。
步骤 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() 函数来执行任务并将字符串的数据类型转换为双精度浮点数。
初始化并定义一个字符串类型的变量并为其赋值。
在下一步中,我们使用 strconv 包中定义的 TypeOf() 函数打印我们刚刚声明的变量的类型。
然后我们使用 fmt.Print() 函数打印数据类型中包含的实际值。
然后我们从 Go 语言的“strconv”包中调用 ParseFloat() 函数,并将字符串传递给该函数以将字符串值转换为双精度浮点数。
现在我们打印了变量的类型,以检查数据类型是否已从字符串更改为双精度浮点数。
现在将结果存储在一个单独的变量中,并使用 fmt.Print() 函数在屏幕上打印它们。
结论
我们已成功编译并执行了 Go 语言程序代码,使用函数将字符串类型变量转换为双精度浮点数。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP