By Stefan Nilsson

The original url: yourbasic.org/golang/conv…

     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

The string is converted to a floating point number

ParseFloat uses the strconv.ParseFloat function to parse a string into floating-point numbers. The precision is determined by specifying the value of the parameter bitSize: float32 is 32 and float64 is 64.

func ParseFloat(s string, bitSize int) (float64, error)
Copy the code

When bitSize is 32, the result is still of type FLOAT64, but it can be converted to FLOAT32 without changing its value.

f := "3.14159265"
ifs, err := strconv.ParseFloat(f, 32); Err == nil {fmt.println (s) // 3.1415927410125732}ifs, err := strconv.ParseFloat(f, 64); Err == nil {FMT.Println(s) // 3.14159265}Copy the code

A floating point number is converted to a string

Use the fmt.sprintf method to format a floating point number as a string.

s := fmt.Sprintf("%f", 123.456) // s == "123.456000"
Copy the code
Formatted output instructions A placeholder
1.234560 e+02 Scientific enumeration %e
123.456000 There’s a decimal point but no exponent %f
123.46 Default width, precision 2 %.2f
␣ ␣ 123.46 Width 8, accuracy 2 % 8.2 f
123.456 (Select %e or %f as appropriate to produce a more compact (no trailing 0) output) %g

Fmt cheat sheet

How to format with fmt


Scan the QR code below to follow the Feed and regularly push the latest posts