String to float
Use the strconv.ParseFloat
function to parse a string as a floating-point number with the precision specified by bitSize
: 32 for float32
, or 64 for float64
.
func ParseFloat(s string, bitSize int) (float64, error)
When bitSize
is 32, the result still has type float64
, but it will be convertible to float32
without changing its value.
f := "3.14159265"
if s, err := strconv.ParseFloat(f, 32); err == nil {
fmt.Println(s) // 3.1415927410125732
}
if s, err := strconv.ParseFloat(f, 64); err == nil {
fmt.Println(s) // 3.14159265
}
Float to string
Use the fmt.Sprintf
method to format a floating-point number as a string.
s := fmt.Sprintf("%f", 123.456) // s == "123.456000"
Formatting | Description | Verb |
---|---|---|
1.234560e+02 | Scientific notation | %e |
123.456000 | Decimal point, no exponent | %f |
123.46 | Default width, precision 2 | %.2f |
␣␣123.46 | Width 8, precision 2 | %8.2f |
123.456 | Exponent as needed, necessary digits only | %g |