Go Reference ยท strings and strconv
Go strconv.FormatInt() and FormatFloat()
Reference for Go strconv.FormatInt, FormatUint, FormatFloat and FormatBool: print numbers in any base, choose precision and format verbs, and use AppendInt.
The Format functions in strconv turn numbers into strings with exact control. FormatInt and FormatUint print an integer in any base from 2 to 36. FormatFloat prints a float using a chosen layout ('f', 'e', 'g', ...) and precision. FormatBool returns "true" or "false".
They are the building blocks behind fmt verbs, but skip the format-string parsing, so they are faster and more explicit.
strconv.FormatInt(255, 16) // "ff" strconv.FormatFloat(3.14159, 'f', 2, 64) // "3.14"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func FormatInt(i int64, base int) string func FormatUint(i uint64, base int) string func FormatFloat(f float64, fmt byte, prec, bitSize int) string func FormatBool(b bool) string
| Name | Description |
|---|---|
i |
The integer to format. FormatInt writes a leading - for negative values. |
base |
2 to 36. Digits above 9 are lower-case letters a to z. Other values panic. |
f |
The float to format. |
fmt |
A format byte: 'f' (no exponent), 'e' / 'E' (exponent), 'g' / 'G' (shortest of the two), 'b', 'x' / 'X' (hexadecimal exponent form). |
prec |
Digits after the decimal point for f, e; significant digits for g. -1 means the smallest number of digits that parses back to the same value. |
bitSize |
32 or 64: the precision of the original value. |
Returns: the formatted string. Special floats print as +Inf, -Inf and NaN.
Panics: an invalid base in FormatInt or FormatUint.
Usage notes
- Prefer
-1precision for data you will read back. It prints0.1for the literal0.1, not0.1000000000000000055.... bitSizematters with-1. Passing afloat32value converted tofloat64with bitSize 32 prints0.1; with 64 it prints the longer true value, as the second example shows.- Rounding:
'f'with fewer digits rounds the exact binary value to nearest, soFormatFloat(2.675, 'f', 2, 64)gives2.67because 2.675 is stored slightly below. - No prefixes or padding.
FormatInt(255, 16)isff, not0xff. Usefmt.Sprintf("%#x", 255)or%08bfor those. Itoashortcut.Itoa(i)isFormatInt(int64(i), 10).Appendforms (AppendInt,AppendUint,AppendFloat,AppendBool) add to an existing[]byte, which avoids allocating a temporary string.- Money: do not use floats for currency; format integers of cents instead.