Involved Source Filesatob.goatoc.goatof.goatoi.gobytealg.goctoa.godecimal.go Package strconv implements conversions to and from string representations
of basic data types.
# Numeric Conversions
The most common numeric conversions are Atoi (string to int) and Itoa (int to string).
i, err := strconv.Atoi("-42")
s := strconv.Itoa(-42)
These assume decimal and the Go int type.
[ParseBool], [ParseFloat], [ParseInt], and [ParseUint] convert strings to values:
b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-42", 10, 64)
u, err := strconv.ParseUint("42", 10, 64)
The parse functions return the widest type (float64, int64, and uint64),
but if the size argument specifies a narrower width the result can be
converted to that narrower type without data loss:
s := "2147483647" // biggest int32
i64, err := strconv.ParseInt(s, 10, 32)
...
i := int32(i64)
[FormatBool], [FormatFloat], [FormatInt], and [FormatUint] convert values to strings:
s := strconv.FormatBool(true)
s := strconv.FormatFloat(3.1415, 'E', -1, 64)
s := strconv.FormatInt(-42, 16)
s := strconv.FormatUint(42, 16)
[AppendBool], [AppendFloat], [AppendInt], and [AppendUint] are similar but
append the formatted value to a destination slice.
# String Conversions
[Quote] and [QuoteToASCII] convert strings to quoted Go string literals.
The latter guarantees that the result is an ASCII string, by escaping
any non-ASCII Unicode with \u:
q := strconv.Quote("Hello, 世界")
q := strconv.QuoteToASCII("Hello, 世界")
[QuoteRune] and [QuoteRuneToASCII] are similar but accept runes and
return quoted Go rune literals.
[Unquote] and [UnquoteChar] unquote Go string and rune literals.eisel_lemire.goftoa.goftoaryu.goisprint.goitoa.goquote.go
Code Examples
package main
import (
"fmt"
"strconv"
)
func main() {
b := []byte("bool:")
b = strconv.AppendBool(b, true)
fmt.Println(string(b))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b32 := []byte("float32:")
b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
fmt.Println(string(b32))
b64 := []byte("float64:")
b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
fmt.Println(string(b64))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b10 := []byte("int (base 10):")
b10 = strconv.AppendInt(b10, -42, 10)
fmt.Println(string(b10))
b16 := []byte("int (base 16):")
b16 = strconv.AppendInt(b16, -42, 16)
fmt.Println(string(b16))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b := []byte("quote:")
b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b := []byte("rune:")
b = strconv.AppendQuoteRune(b, '☺')
fmt.Println(string(b))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b := []byte("rune (ascii):")
b = strconv.AppendQuoteRuneToASCII(b, '☺')
fmt.Println(string(b))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b := []byte("quote (ascii):")
b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
fmt.Println(string(b))
}
package main
import (
"fmt"
"strconv"
)
func main() {
b10 := []byte("uint (base 10):")
b10 = strconv.AppendUint(b10, 42, 10)
fmt.Println(string(b10))
b16 := []byte("uint (base 16):")
b16 = strconv.AppendUint(b16, 42, 16)
fmt.Println(string(b16))
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := "10"
if s, err := strconv.Atoi(v); err == nil {
fmt.Printf("%T, %v", s, s)
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))
fmt.Println(strconv.CanBackquote("`can't backquote this`"))
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := true
s := strconv.FormatBool(v)
fmt.Printf("%T, %v\n", s, s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := 3.1415926535
s32 := strconv.FormatFloat(v, 'E', -1, 32)
fmt.Printf("%T, %v\n", s32, s32)
s64 := strconv.FormatFloat(v, 'E', -1, 64)
fmt.Printf("%T, %v\n", s64, s64)
// fmt.Println uses these arguments to print floats
fmt64 := strconv.FormatFloat(v, 'g', -1, 64)
fmt.Printf("%T, %v\n", fmt64, fmt64)
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := int64(-42)
s10 := strconv.FormatInt(v, 10)
fmt.Printf("%T, %v\n", s10, s10)
s16 := strconv.FormatInt(v, 16)
fmt.Printf("%T, %v\n", s16, s16)
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := uint64(42)
s10 := strconv.FormatUint(v, 10)
fmt.Printf("%T, %v\n", s10, s10)
s16 := strconv.FormatUint(v, 16)
fmt.Printf("%T, %v\n", s16, s16)
}
package main
import (
"fmt"
"strconv"
)
func main() {
shamrock := strconv.IsGraphic('☘')
fmt.Println(shamrock)
a := strconv.IsGraphic('a')
fmt.Println(a)
bel := strconv.IsGraphic('\007')
fmt.Println(bel)
}
package main
import (
"fmt"
"strconv"
)
func main() {
c := strconv.IsPrint('\u263a')
fmt.Println(c)
bel := strconv.IsPrint('\007')
fmt.Println(bel)
}
package main
import (
"fmt"
"strconv"
)
func main() {
i := 10
s := strconv.Itoa(i)
fmt.Printf("%T, %v\n", s, s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
str := "Not a number"
if _, err := strconv.ParseFloat(str, 64); err != nil {
e := err.(*strconv.NumError)
fmt.Println("Func:", e.Func)
fmt.Println("Num:", e.Num)
fmt.Println("Err:", e.Err)
fmt.Println(err)
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := "true"
if s, err := strconv.ParseBool(v); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := "3.1415926535"
if s, err := strconv.ParseFloat(v, 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat(v, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("NaN", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
// ParseFloat is case insensitive
if s, err := strconv.ParseFloat("nan", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("inf", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("+Inf", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("-Inf", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("-0", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseFloat("+0", 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
v32 := "-354634382"
if s, err := strconv.ParseInt(v32, 10, 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseInt(v32, 16, 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
v64 := "-3546343826724305832"
if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseInt(v64, 16, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
v := "42"
if s, err := strconv.ParseUint(v, 10, 32); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
if s, err := strconv.ParseUint(v, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
}
package main
import (
"fmt"
"strconv"
)
func main() {
// This string literal contains a tab character.
s := strconv.Quote(`"Fran & Freddie's Diner ☺"`)
fmt.Println(s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
s := strconv.QuoteRune('☺')
fmt.Println(s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
s := strconv.QuoteRuneToASCII('☺')
fmt.Println(s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
s := strconv.QuoteRuneToGraphic('☺')
fmt.Println(s)
s = strconv.QuoteRuneToGraphic('\u263a')
fmt.Println(s)
s = strconv.QuoteRuneToGraphic('\u000a')
fmt.Println(s)
s = strconv.QuoteRuneToGraphic(' ') // tab character
fmt.Println(s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
// This string literal contains a tab character.
s := strconv.QuoteToASCII(`"Fran & Freddie's Diner ☺"`)
fmt.Println(s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
s := strconv.QuoteToGraphic("☺")
fmt.Println(s)
// This string literal contains a tab character.
s = strconv.QuoteToGraphic("This is a \u263a \u000a")
fmt.Println(s)
s = strconv.QuoteToGraphic(`" This is a ☺ \n "`)
fmt.Println(s)
}
package main
import (
"fmt"
"strconv"
)
func main() {
s, err := strconv.Unquote("You can't unquote a string without quotes")
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("\"The string must be either double-quoted\"")
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("`or backquoted.`")
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("'\u263a'") // single character only allowed in single quotes
fmt.Printf("%q, %v\n", s, err)
s, err = strconv.Unquote("'\u2639\u2639'")
fmt.Printf("%q, %v\n", s, err)
}
package main
import (
"fmt"
"log"
"strconv"
)
func main() {
v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')
if err != nil {
log.Fatal(err)
}
fmt.Println("value:", string(v))
fmt.Println("multibyte:", mb)
fmt.Println("tail:", t)
}
Package-Level Type Names (total 5, in which 1 is exported)
/* sort exporteds by: | */
A NumError records a failed conversion. // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.) // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat, ParseComplex) // the input(*NumError) Error() string(*NumError) Unwrap() error
*NumError : error
*NumError : github.com/go-faster/errors.Wrapper
func baseError(fn, str string, base int) *NumError
func bitSizeError(fn, str string, bitSize int) *NumError
func rangeError(fn, str string) *NumError
func syntaxError(fn, str string) *NumError
// digits, big-endian representation // decimal point // number of digits used // negative flag // discarded nonzero digits beyond d[:nd] Assign v to a. Round a to nd digits (or fewer).
If nd is zero, it means we're rounding
just to the left of the digits, as in
0.09 -> 0.1. Round a down to nd digits (or fewer). Round a up to nd digits (or fewer). Extract integer part, rounded appropriately.
No guarantees about overflow. Binary shift left (k > 0) or right (k < 0).(*decimal) String() string(*decimal) floatBits(flt *floatInfo) (b uint64, overflow bool)(*decimal) set(s string) (ok bool)
*decimal : fmt.Stringer
*decimal : context.stringer
*decimal : runtime.stringer
func leftShift(a *decimal, k uint)
func rightShift(a *decimal, k uint)
func roundShortest(d *decimal, mant uint64, exp int, flt *floatInfo)
func shouldRoundUp(a *decimal, nd int) bool
func trim(a *decimal)
// minus one digit if original < a. // number of new digits
Package-Level Functions (total 97, in which 34 are exported)
AppendBool appends "true" or "false", according to the value of b,
to dst and returns the extended buffer.
AppendFloat appends the string form of the floating-point number f,
as generated by FormatFloat, to dst and returns the extended buffer.
AppendInt appends the string form of the integer i,
as generated by FormatInt, to dst and returns the extended buffer.
AppendQuote appends a double-quoted Go string literal representing s,
as generated by Quote, to dst and returns the extended buffer.
AppendQuoteRune appends a single-quoted Go character literal representing the rune,
as generated by QuoteRune, to dst and returns the extended buffer.
AppendQuoteRuneToASCII appends a single-quoted Go character literal representing the rune,
as generated by QuoteRuneToASCII, to dst and returns the extended buffer.
AppendQuoteRuneToGraphic appends a single-quoted Go character literal representing the rune,
as generated by QuoteRuneToGraphic, to dst and returns the extended buffer.
AppendQuoteToASCII appends a double-quoted Go string literal representing s,
as generated by QuoteToASCII, to dst and returns the extended buffer.
AppendQuoteToGraphic appends a double-quoted Go string literal representing s,
as generated by QuoteToGraphic, to dst and returns the extended buffer.
AppendUint appends the string form of the unsigned integer i,
as generated by FormatUint, to dst and returns the extended buffer.
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
CanBackquote reports whether the string s can be represented
unchanged as a single-line backquoted string without control
characters other than tab.
FormatBool returns "true" or "false" according to the value of b.
FormatComplex converts the complex number c to a string of the
form (a+bi) where a and b are the real and imaginary parts,
formatted according to the format fmt and precision prec.
The format fmt and precision prec have the same meaning as in FormatFloat.
It rounds the result assuming that the original was obtained from a complex
value of bitSize bits, which must be 64 for complex64 and 128 for complex128.
FormatFloat converts the floating-point number f to a string,
according to the format fmt and precision prec. It rounds the
result assuming that the original was obtained from a floating-point
value of bitSize bits (32 for float32, 64 for float64).
The format fmt is one of
'b' (-ddddp±ddd, a binary exponent),
'e' (-d.dddde±dd, a decimal exponent),
'E' (-d.ddddE±dd, a decimal exponent),
'f' (-ddd.dddd, no exponent),
'g' ('e' for large exponents, 'f' otherwise),
'G' ('E' for large exponents, 'f' otherwise),
'x' (-0xd.ddddp±ddd, a hexadecimal fraction and binary exponent), or
'X' (-0Xd.ddddP±ddd, a hexadecimal fraction and binary exponent).
The precision prec controls the number of digits (excluding the exponent)
printed by the 'e', 'E', 'f', 'g', 'G', 'x', and 'X' formats.
For 'e', 'E', 'f', 'x', and 'X', it is the number of digits after the decimal point.
For 'g' and 'G' it is the maximum number of significant digits (trailing
zeros are removed).
The special precision -1 uses the smallest number of digits
necessary such that ParseFloat will return f exactly.
FormatInt returns the string representation of i in the given base,
for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
for digit values >= 10.
FormatUint returns the string representation of i in the given base,
for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
for digit values >= 10.
IsGraphic reports whether the rune is defined as a Graphic by Unicode. Such
characters include letters, marks, numbers, punctuation, symbols, and
spaces, from categories L, M, N, P, S, and Zs.
IsPrint reports whether the rune is defined as printable by Go, with
the same definition as unicode.IsPrint: letters, numbers, punctuation,
symbols and ASCII space.
Itoa is equivalent to FormatInt(int64(i), 10).
ParseBool returns the boolean value represented by the string.
It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.
Any other value returns an error.
ParseComplex converts the string s to a complex number
with the precision specified by bitSize: 64 for complex64, or 128 for complex128.
When bitSize=64, the result still has type complex128, but it will be
convertible to complex64 without changing its value.
The number represented by s must be of the form N, Ni, or N±Ni, where N stands
for a floating-point number as recognized by ParseFloat, and i is the imaginary
component. If the second N is unsigned, a + sign is required between the two components
as indicated by the ±. If the second N is NaN, only a + sign is accepted.
The form may be parenthesized and cannot contain any spaces.
The resulting complex number consists of the two components converted by ParseFloat.
The errors that ParseComplex returns have concrete type *NumError
and include err.Num = s.
If s is not syntactically well-formed, ParseComplex returns err.Err = ErrSyntax.
If s is syntactically well-formed but either component is more than 1/2 ULP
away from the largest floating point number of the given component's size,
ParseComplex returns err.Err = ErrRange and c = ±Inf for the respective component.
ParseFloat converts the string s to a floating-point number
with the precision specified by bitSize: 32 for float32, or 64 for float64.
When bitSize=32, the result still has type float64, but it will be
convertible to float32 without changing its value.
ParseFloat accepts decimal and hexadecimal floating-point numbers
as defined by the Go syntax for [floating-point literals].
If s is well-formed and near a valid floating-point number,
ParseFloat returns the nearest floating-point number rounded
using IEEE754 unbiased rounding.
(Parsing a hexadecimal floating-point value only rounds when
there are more bits in the hexadecimal representation than
will fit in the mantissa.)
The errors that ParseFloat returns have concrete type *NumError
and include err.Num = s.
If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.
If s is syntactically well-formed but is more than 1/2 ULP
away from the largest floating point number of the given size,
ParseFloat returns f = ±Inf, err.Err = ErrRange.
ParseFloat recognizes the string "NaN", and the (possibly signed) strings "Inf" and "Infinity"
as their respective special floating point values. It ignores case when matching.
[floating-point literals]: https://go.dev/ref/spec#Floating-point_literals
ParseInt interprets a string s in the given base (0, 2 to 36) and
bit size (0 to 64) and returns the corresponding value i.
The string may begin with a leading sign: "+" or "-".
If the base argument is 0, the true base is implied by the string's
prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o",
16 for "0x", and 10 otherwise. Also, for argument base 0 only,
underscore characters are permitted as defined by the Go syntax for
[integer literals].
The bitSize argument specifies the integer type
that the result must fit into. Bit sizes 0, 8, 16, 32, and 64
correspond to int, int8, int16, int32, and int64.
If bitSize is below 0 or above 64, an error is returned.
The errors that ParseInt returns have concrete type *NumError
and include err.Num = s. If s is empty or contains invalid
digits, err.Err = ErrSyntax and the returned value is 0;
if the value corresponding to s cannot be represented by a
signed integer of the given size, err.Err = ErrRange and the
returned value is the maximum magnitude integer of the
appropriate bitSize and sign.
[integer literals]: https://go.dev/ref/spec#Integer_literals
ParseUint is like ParseInt but for unsigned numbers.
A sign prefix is not permitted.
Quote returns a double-quoted Go string literal representing s. The
returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
control characters and non-printable characters as defined by
IsPrint.
QuotedPrefix returns the quoted string (as understood by Unquote) at the prefix of s.
If s does not start with a valid quoted string, QuotedPrefix returns an error.
QuoteRune returns a single-quoted Go character literal representing the
rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100)
for control characters and non-printable characters as defined by IsPrint.
If r is not a valid Unicode code point, it is interpreted as the Unicode
replacement character U+FFFD.
QuoteRuneToASCII returns a single-quoted Go character literal representing
the rune. The returned string uses Go escape sequences (\t, \n, \xFF,
\u0100) for non-ASCII characters and non-printable characters as defined
by IsPrint.
If r is not a valid Unicode code point, it is interpreted as the Unicode
replacement character U+FFFD.
QuoteRuneToGraphic returns a single-quoted Go character literal representing
the rune. If the rune is not a Unicode graphic character,
as defined by IsGraphic, the returned string will use a Go escape sequence
(\t, \n, \xFF, \u0100).
If r is not a valid Unicode code point, it is interpreted as the Unicode
replacement character U+FFFD.
QuoteToASCII returns a double-quoted Go string literal representing s.
The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
non-ASCII characters and non-printable characters as defined by IsPrint.
QuoteToGraphic returns a double-quoted Go string literal representing s.
The returned string leaves Unicode graphic characters, as defined by
IsGraphic, unchanged and uses Go escape sequences (\t, \n, \xFF, \u0100)
for non-graphic characters.
Unquote interprets s as a single-quoted, double-quoted,
or backquoted Go string literal, returning the string value
that s quotes. (If s is single-quoted, it would be a Go
character literal; Unquote returns the corresponding
one-character string.)
UnquoteChar decodes the first character or byte in the escaped string
or character literal represented by the string s.
It returns four values:
1. value, the decoded Unicode code point or byte value;
2. multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
3. tail, the remainder of the string after the character; and
4. an error that will be nil if the character is syntactically valid.
The second argument, quote, specifies the type of literal being parsed
and therefore which escaped quote character is permitted.
If set to a single quote, it permits the sequence \' and disallows unescaped '.
If set to a double quote, it permits \" and disallows unescaped ".
If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.
If possible to convert decimal representation to 64-bit float f exactly,
entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
Three common cases:
value is exact integer
value is exact integer * exact power of ten
value is exact integer / exact power of ten
These all produce potentially inexact but correctly rounded answers.
atofHex converts the hex floating-point string s
to a rounded float32 or float64 value (depending on flt==&float32info or flt==&float64info)
and returns it as a float64.
The string s has already been parsed into a mantissa, exponent, and sign (neg==true for negative).
If trunc is true, trailing non-zero bits have been omitted from the mantissa.
bsearch16 returns the smallest i such that a[i] >= x.
If there is no such i, bsearch16 returns len(a).
bsearch32 returns the smallest i such that a[i] >= x.
If there is no such i, bsearch32 returns len(a).
cloneString returns a string copy of x.
All ParseXXX functions allow the input string to escape to the error value.
This hurts strconv.ParseXXX(string(b)) calls where b is []byte since
the conversion from []byte must allocate a string on the heap.
If we assume errors are infrequent, then we can avoid escaping the input
back to the output by copying it first. This allows the compiler to call
strconv.ParseXXX without a heap allocation for most []byte to string
conversions, since it can now prove that the string cannot escape Parse.
TODO: Use strings.Clone instead? However, we cannot depend on "strings"
since it incurs a transitive dependency on "unicode".
Either move strings.Clone to an internal/bytealg or make the
"strings" to "unicode" dependency lighter (see https://go.dev/issue/54098).
commonPrefixLenIgnoreCase returns the length of the common
prefix of s and prefix, with the character case of s ignored.
The prefix argument must be all lower-case.
computeBounds returns a floating-point vector (l, c, u)×2^e2
where the mantissas are 55-bit (or 26-bit) integers, describing the interval
represented by the input float64 or float32.
contains reports whether the string contains the byte c.
convErr splits an error returned by parseFloatPrefix
into a syntax or range error for ParseComplex.
%x: -0x1.yyyyyyyyp±ddd or -0x0p+0. (y is hex digit, d is decimal digit)
formatBits computes the string representation of u in the given base.
If neg is set, u is treated as negative int64 value. If append_ is
set, the string is appended to dst and the resulting byte slice is
returned as the first result value; otherwise the string is returned
as the second result value.
formatDecimal fills d with at most prec decimal digits
of mantissa m. The boolean trunc indicates whether m
is truncated compared to the original number being formatted.
index returns the index of the first instance of c in s, or -1 if missing.
isInGraphicList reports whether the rune is in the isGraphic list. This separation
from IsGraphic allows quoteWith to avoid two calls to IsPrint.
Should be called only if IsPrint fails.
Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow.
lower(c) is a lower-case letter if and only if
c is either that lower-case letter or the equivalent upper-case letter.
Instead of writing c == 'x' || c == 'X' one can write lower(c) == 'x'.
Note that lower of non-letters can produce other non-letters.
mulByLog10Log2 returns math.Floor(x * log(10)/log(2)) for an integer x in
the range -500 <= x && x <= +500.
The range restriction lets us work in faster integer arithmetic instead of
slower floating point arithmetic. Correctness is verified by unit tests.
mulByLog2Log10 returns math.Floor(x * log(2)/log(10)) for an integer x in
the range -1600 <= x && x <= +1600.
The range restriction lets us work in faster integer arithmetic instead of
slower floating point arithmetic. Correctness is verified by unit tests.
mult128bitPow10 takes a floating-point input with a 55-bit
mantissa and multiplies it with 10^q. The resulting mantissa
is m*P >> 119 where P is a 128-bit element of the detailedPowersOfTen tables.
It is typically 63 or 64-bit wide.
The returned boolean is true is all trimmed bits were zero.
That is:
m*2^e2 * round(10^q) = resM * 2^resE + ε
exact = ε == 0
mult64bitPow10 takes a floating-point input with a 25-bit
mantissa and multiplies it with 10^q. The resulting mantissa
is m*P >> 57 where P is a 64-bit element of the detailedPowersOfTen tables.
It is typically 31 or 32-bit wide.
The returned boolean is true if all trimmed bits were zero.
That is:
m*2^e2 * round(10^q) = resM * 2^resE + ε
exact = ε == 0
readFloat reads a decimal or hexadecimal mantissa and exponent from a float
string representation in s; the number may be followed by other characters.
readFloat reports the number of bytes consumed (i), and whether the number
is valid (ok).
Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow.
roundShortest rounds d (= mant * 2^exp) to the shortest number of digits
that will let the original floating point value be precisely reconstructed.
ryuDigits32 emits decimal digits for a number less than 1e9.
ryuFtoaFixed32 formats mant*(2^exp) with prec decimal digits.
ryuFtoaFixed64 formats mant*(2^exp) with prec decimal digits.
ryuFtoaShortest formats mant*2^exp with prec decimal digits.
If we chop a at nd digits, should we round up?
small returns the string for an i with 0 <= i < nSmalls.
special returns the floating-point value for the special,
possibly signed floating-point representations inf, infinity,
and NaN. The result is ok if a prefix of s contains one
of these representations and n is the length of that prefix.
The character case is ignored.
trim trailing zeros from number.
(They are meaningless; the decimal point is tracked
independent of the number of digits.)
underscoreOK reports whether the underscores in s are allowed.
Checking them in this one function lets all the parsers skip over them simply.
Underscore must appear only between digits or between a base prefix and a digit.
unquote parses a quoted string at the start of the input,
returning the parsed prefix, the remaining suffix, and any parse errors.
If unescape is true, the parsed prefix is unescaped,
otherwise the input prefix is provided verbatim.
Package-Level Variables (total 16, in which 2 are exported)
ErrRange indicates that a value is out of range for the target type.
ErrSyntax indicates that a value does not have the right syntax for the target type.
detailedPowersOfTen contains 128-bit mantissa approximations (rounded down)
to the powers of 10. For example:
- 1e43 ≈ (0xE596B7B0_C643C719 * (2 ** 79))
- 1e43 = (0xE596B7B0_C643C719_6D9CCD05_D0000000 * (2 ** 15))
The mantissas are explicitly listed. The exponents are implied by a linear
expression with slope 217706.0/65536.0 ≈ log(10)/log(2).
The table was generated by
https://github.com/google/wuffs/blob/ba3818cb6b473a2ed0b38ecfc07dbbd3a97e8ae7/script/print-mpb-powers-of-10.go
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.