Convert between float and string

yourbasic.org/golang
     3.141592653589793238462643383279
   5028841971693993751058209749445923
  07816406286208998628034825342117067
  9821    48086         5132
 823      06647        09384
46        09550        58223
17        25359        4081
          2848         1117
          4502         8410
          2701         9385
         21105        55964
         46229        48954
         9303         81964
         4288         10975
        66593         34461
       284756         48233
       78678          31652        71
      2019091         456485       66
     9234603           48610454326648
    2133936            0726024914127
    3724587             00660631558
    817488               152092096

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

Fmt cheat sheet

How to format with fmt

Share this page: