Go 또는 Golang에서 문자열 유형 값을 float 유형 값으로 변환하는 방법은 무엇입니까?
11872 단어 go
string 유형 값을 float 유형 값으로 변환하려면 Go 또는 Golang의 ParseFloat() 표준 패키지에서 strconv 메서드를 사용할 수 있습니다.ParseFloat() 방법:string 유형 값을 첫 번째 인수로 허용합니다int 유형 값의 비트 크기float 유형 값이고 두 번째 값은 error 데이터입니다(있는 경우). TL;DR
package main
// import `strconv` package
import (
"fmt"
"strconv"
)
func main() {
// convert `string` type value of "33.96"
// using the `ParseFloat()` method and passing
// the value "33.96" as its first argument
// 64, the bit size as its second argument
convertedFloatNum, err := strconv.ParseFloat("33.96", 64)
// check if any error happened
if err != nil {
fmt.Println(err.Error())
return
}
// log output of the `convertedFloatNum`
// variable to the console
fmt.Println(convertedFloatNum) // 33.96 and the type is float ✅
}
예를 들어
string의 "33.96" 유형 값을 해당하는 float 유형 값으로 변환해야 한다고 가정해 보겠습니다.이를 위해 먼저
strconv 표준 패키지를 다음과 같이 가져옵니다.package main
// import `strconv` package
import "strconv"
패키지를 가져온 후
main() 함수 내에서 ParseFloat() 패키지의 strconv 메서드를 사용하고 string의 "33.96" 유형 값을 첫 번째 인수로 전달하고 64 비트 크기를 다음과 같이 전달할 수 있습니다. 함수에 대한 세 번째 인수입니다.다음과 같이 할 수 있습니다.
package main
// import `strconv` package
import "strconv"
func main(){
// convert `string` type value of "33.96"
// using the `ParseFloat()` method and passing
// the value "33.96" as its first argument
// 64, the bit size as its second argument
strconv.ParseFloat("33.96", 64)
}
ParseFloat() 메서드는 성공적으로 변환된 경우 첫 번째 값이 변환된 float 유형 값이고 두 번째 값이 변환 중에 발생한 경우 error 데이터인 2개의 값을 반환합니다. 이 2개의 데이터를 캡처하기 위해 2개의 변수를 할당해 보겠습니다.다음과 같이 할 수 있습니다.
package main
// import `strconv` package
import "strconv"
func main(){
// convert `string` type value of "33.96"
// using the `ParseFloat()` method and passing
// the value "33.96" as its first argument
// 64, the bit size as its second argument
convertedFloatNum, err := strconv.ParseFloat("33.96", 64)
}
변환된 값
float을 처리하기 전에 변환 프로세스 중에 오류가 있었는지 확인해야 합니다. 간단한 if 조건문을 사용하여 err 데이터 변수가 nil인지 확인합니다. 그렇지 않은 경우nil 변환 중에 오류가 발생한 것입니다.다음과 같이 할 수 있습니다.
package main
// import `strconv` package
import (
"fmt"
"strconv"
)
func main(){
// convert `string` type value of "33.96"
// using the `ParseFloat()` method and passing
// the value "33.96" as its first argument
// 64, the bit size as its second argument
convertedFloatNum, err := strconv.ParseFloat("33.96", 64)
// check if any error happened
if err != nil {
fmt.Println(err.Error())
return
}
}
오류가 없으면
convertedFloatNum 변수에 변환된 float 유형 값이 있어야 한다고 가정하는 것이 안전합니다. 다음과 같이 출력을 콘솔에 기록해 보겠습니다.package main
// import `strconv` package
import (
"fmt"
"strconv"
)
func main() {
// convert `string` type value of "33.96"
// using the `ParseFloat()` method and passing
// the value "33.96" as its first argument
// 64, the bit size as its second argument
convertedFloatNum, err := strconv.ParseFloat("33.96", 64)
// check if any error happened
if err != nil {
fmt.Println(err.Error())
return
}
// log output of the `convertedFloatNum`
// variable to the console
fmt.Println(convertedFloatNum) // 33.96 and the type is float ✅
}
보시다시피
string의 "33.96" 유형 값이 우리가 원하는 해당 float 유형 값으로 성공적으로 변환되었습니다.The Go Playground에 있는 위의 코드를 참조하십시오.
이제
string와 같이 알파벳으로 구성된 John Doe type 값을 주고 이를 float type 값으로 변환해 봅시다.package main
// import `strconv` package
import (
"fmt"
"strconv"
)
func main() {
// convert `string` type value of "John Doe"
// using the `ParseFloat()` method and passing
// the value "John Doe" as its first argument
// 64, the bit size as its third argument
convertedFloatNum, err := strconv.ParseFloat("John Doe", 64) // Error ❌. strconv.ParseFloat: parsing "John Doe": invalid syntax
// check if any error happened
if err != nil {
fmt.Println(err.Error())
return
}
// log output of the `convertedFloatNum`
// variable to the console
fmt.Println(convertedFloatNum)
}
보시다시피 Go 컴파일러는
strconv.ParseFloat: parsing "John Doe": invalid syntax라는 오류를 표시합니다. 이는 본질적으로 이 값을 해당하는 float 유형 값으로 구문 분석할 수 없음을 의미합니다.The Go Playground에 있는 위의 코드를 참조하십시오.
그게 다야 😃!
이 정보가 유용하다고 생각되면 자유롭게 공유하세요 😃.
Reference
이 문제에 관하여(Go 또는 Golang에서 문자열 유형 값을 float 유형 값으로 변환하는 방법은 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/melvin2016/how-to-convert-a-string-type-value-to-a-float-type-value-in-go-or-golang-4kjl텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)