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 語言程式程式碼,使用函式將字串型別變數轉換為雙精度浮點數。

更新時間: 2022年11月14日

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.