Skip to content

strconv #

Description

strconv provides functions for converting strings to numbers and numbers to strings.

Integer parsing

parse_int and parse_uint accept an explicit base from 2 to 36, or base 0 for prefix inference: 0b selects binary, 0o or a bare leading 0 selects octal, and 0x selects hexadecimal. Other inputs use decimal. Use base 10 when leading zeros should remain decimal digits.

import strconv

assert strconv.parse_int('0777', 0, 64)! == 511
assert strconv.parse_uint('010', 0, 64)! == 8
assert strconv.parse_int('0777', 10, 64)! == 777

Digits must be valid for the selected base, so 08 and 09 fail with base 0. An explicit prefix, with its optional underscore separator, must be followed by digits. Empty strings and a sign without digits are syntax errors for parse_int and parse_uint. The string conveniences .int(), .i64() and their narrower variants still return 0 for ''. V integer literal analysis keeps bare leading zeros decimal; octal literals use 0o.

Bit size 0 uses the width of int in the selected target and backend, as given by sizeof(int) * 8. Explicit bit sizes from 1 to 64 select that many bits regardless of the target. parse_int saturates at the signed limits; parse_uint reports overflow as an error. atoi and string.int() retain their 32-bit range even on targets with a 64-bit int.

String numeric conveniences such as .int(), .i64(), .u64(), and their narrower variants also keep bare leading zeros decimal. Explicit 0b, 0o, and 0x prefixes still select a base. Use .parse_int(0, bits) or .parse_uint(0, bits) for base-zero inference on a string.

Underscores may separate digits, as in 1_000 or 0xFF_FF, with base 0 only: with an explicit base, parse_int and parse_uint return an error for them. The lower-level common_parse_int, common_parse_uint and common_parse_uint2 accept the separators in every base; .int() and the other string conveniences below use them, so '1_000'.int() is 1000.

assert '010'.int() == 10
assert '0o10'.int() == 8
assert '010'.parse_int(0, 64)! == 8

Floating-point parsing

On the C backend, atof64 parses decimal numbers with an optional sign, decimal point, and exponent. Underscores may separate digits, as in 1_000 or 1.2_5e1_0. It also accepts case-insensitive nan, inf, and infinity, with an optional sign for infinity. Whitespace, bare signs, missing digits, and misplaced underscores return an error. Conversion retains up to 18 significant decimal digits and rounds binary halfway cases to the nearest value with an even significand. Subnormal results use the same rounding rule.

import strconv
import math

assert strconv.atof64('1_000')! == 1000.0
assert math.is_inf(strconv.atof64('-inf')!, -1)
assert math.is_nan(strconv.atof64('NaN')!)

On the C backend, allow_extra_chars: true permits trailing characters after a decimal number, for example atof64('1.5units', allow_extra_chars: true) returns 1.5. A mantissa and any exponent must still contain digits.

On the C backend, a number whose magnitude is too large for an f64, such as 1e400, returns a value out of range error, so that it cannot be mistaken for an inf in the input. Pass allow_overflow: true to get +inf or -inf for such a number instead; string.f64() and string.f32(), which have no error to return, do that. The inf and infinity spellings never return this error. A number too small for an f64, such as 1e-400, is not an error: it rounds to a subnormal value or to a signed zero.

import strconv
import math

if value := strconv.atof64('1e400') {
    assert false, 'parsed as ${value}'
} else {
    assert err.msg() == 'strconv.atof64: parsing "1e400": value out of range'
}
assert math.is_inf(strconv.atof64('-1e400', allow_overflow: true)!, -1)
assert strconv.atof64('1.7976931348623157e308')! == math.max_f64
assert strconv.atof64('1e-400')! == 0.0

Integer formatting

format_int and format_uint represent signed and unsigned integers in any radix from 2 to 36. Digits above 9 use lowercase letters; negative signed values keep a leading minus sign, including min_i64.

import strconv

assert strconv.format_int(min_i64, 16) == '-8000000000000000'
assert strconv.format_uint(max_u64, 16) == 'ffffffffffffffff'

Scientific floating-point formatting

On the C backend, f32_to_str_pad and f64_to_str_pad format a value in scientific notation with the requested number of digits after the decimal point. A zero or negative precision omits the decimal point, while preserving the exponent. Zero values receive the requested padding, and a rounding carry adjusts the exponent.

import strconv

assert strconv.f64_to_str_pad(9.5, 0) == '1e+01'
assert strconv.f64_to_str_pad(0.0, 3) == '0.000e+00'
assert strconv.f32_to_str_pad(999984.0, 1) == '1.0e+06'

These functions round the shortest decimal representation half up, then append zeros as needed. They do not round the exact binary value like C's printf: for example, f64_to_str_pad(0.1, 20) gives 1.00000000000000000000e-01.

On the C backend, format_es rounds the exact binary f64 value to the requested scientific precision half up. This preserves subnormal digits: format_es(5e-324, len1: 2) returns 4.94e-324. Zero precision omits the decimal point; zero values receive the requested padding. BF_param.positive supplies the sign, including for negative zero, when calling format_es directly. The shortest-form f64_to_str_pad behaviour described above is unchanged.

Buffer formatting

On the C backend, format_fl and f64_to_str_lnd1 format the exact binary f64 value in fixed decimal notation, rounded to the requested fractional precision half up. Large integer values retain every digit, and precision can expose digits beyond the shortest decimal representation: format_fl(0.1, len1: 20) returns 0.10000000000000000555. BF_param.positive supplies the sign when calling format_fl directly.

write_dec and write_dec_u write a decimal integer into a caller-provided []u8 buffer. They return the number of bytes written, or -1 when the buffer is too small.

import strconv

mut buf := []u8{len: 20}
n := strconv.write_dec(-12345, mut buf)
assert n == 6
assert buf[..n].bytestr() == '-12345'

Thousands separators

format_thousands formats built-in integer and floating-point values with a thousands separator. Pass a string for the integer separator, or a Separator to configure both integer and decimal separators.

import strconv

assert strconv.format_thousands(1234567, ' ') == '1 234 567'
assert strconv.format_thousands(1234567.89, strconv.Separator{
    integer: '.'
    decimal: ','
}) == '1.234.567,89'

The numeric type is checked at compile time; unsupported types produce a compile-time error.

add_thousands_sep groups the integer part of an already formatted numeric string, preserving its sign, fraction, and exponent. It accepts the same separator options. Unlike the numeric API, the string API keeps scientific notation as supplied.

import strconv

assert strconv.add_thousands_sep('1234567.89', ',') == '1,234,567.89'
assert strconv.add_thousands_sep('1.5e+21', ',') == '1.5e+21'
assert strconv.add_thousands_sep('-12345.5', strconv.Separator{
    integer: '.'
    decimal: ','
}) == '-12.345,5'

Quoting strings and runes

quote returns a double-quoted Go-syntax string literal for a string, and quote_rune a single-quoted Go rune literal for one rune. Control characters and non-printable runes become Go escape sequences; everything else is kept as it is, so UTF-8 text stays readable in the output. The result follows Go's syntax rather than V's: $ is not escaped, so quote('\${x}') returns "${x}", which V would read as an interpolation.

import strconv

assert strconv.quote('café') == '"café"'
assert strconv.quote('a\tb') == '"a\\tb"'
assert strconv.quote_rune(`A`) == "'A'"
assert strconv.quote_rune(`é`) == "'é'"

The *_to_ascii variants escape every non-ASCII rune as \u or \U, and the *_to_graphic variants escape only the runes is_graphic rejects, so they keep spaces such as U+00A0 that quote escapes.

import strconv

assert strconv.quote_to_ascii('café') == '"caf\\u00e9"'
assert strconv.quote('a b') == '"a\\u00a0b"'
assert strconv.quote_to_graphic('a b') == '"a b"'

Each function has an append_ form that writes into a []u8 the caller already owns instead of allocating a new string, which is what you want inside a loop.

import strconv

mut buf := 'log: '.bytes()
for word in ['a', 'b\tc'] {
    strconv.append_quote(mut buf, word)
    buf << ` `
}
assert buf.bytestr() == 'log: "a" "b\\tc" '

is_print and is_graphic answer the two questions those functions ask, and can_backquote reports whether a string can be written unchanged as a Go raw string literal, between backquotes. That rules out control characters other than tab, the backquote itself, DEL, invalid UTF-8 and the byte order mark; a backslash is fine, since a raw string has no escapes.

import strconv

assert strconv.is_print(`a`)
assert !strconv.is_print(0x07)
assert !strconv.is_print(0x00A0)
assert strconv.is_graphic(0x00A0)
assert !strconv.is_graphic(0x00AD)
assert strconv.can_backquote('a\\b')
assert !strconv.can_backquote('a`b')

The lookup tables in printable_tables.v are generated from Go 1.26.1's unicode.IsPrint and unicode.IsGraphic (Unicode 15.0.0) by testdata/gen_quote_data.go, which also produces the expected results the tests compare against. is_print, is_graphic and can_backquote are each checked against Go over every code point from 0 to 0x10FFFF.

Unquoting literals

unquote returns the string value a Go-syntax literal spells. It accepts a double-quoted, single-quoted or backquoted (raw) form, and fails on an unterminated literal or an invalid escape. quoted_prefix reads only the literal at the start of its input and returns it verbatim, quotes included, which is what you want when parsing a stream.

import strconv

assert strconv.unquote('"a\\tb"') or { '?' } == 'a\tb'
assert strconv.unquote('`raw`') or { '?' } == 'raw'
assert strconv.quoted_prefix('"a" then more') or { '?' } == '"a"'

A single-quoted literal holds exactly one character, and a raw literal drops any carriage return inside it.

import strconv

assert strconv.unquote("'a'") or { '?' } == 'a'
assert strconv.unquote("'ab'") or { '?' } == '?'
assert strconv.unquote('`a\rb`') or { '?' } == 'ab'

unquote_char decodes one character and returns it together with whether it was written as a multi-byte sequence and the input that followed it. quote must be the quote byte of the literal the input comes from.

import strconv

r := strconv.unquote_char('\\x41BC', `"`) or { return }

assert r.value == `A`
assert r.multibyte == false
assert r.tail == 'BC'

Like the quoting functions, all three are checked against Go 1.26.1: over 21760 generated literals (every byte in all three quote styles, and every two-byte body whose second byte is 0x00-0x28 in the two quoted styles), and over 54 hand-picked inputs covering the numeric escape forms and their boundaries, invalid UTF-8, multi-byte runes and the error cases.

On the C backend, fxx_to_str_l_parse and fxx_to_str_l_parse_with_dot return inf, +inf, -inf, and nan unchanged when expanding a scientific-format string to decimal notation.

Boolean parsing

parse_bool accepts 1, t, T, true, TRUE, and True as true, and 0, f, F, false, FALSE, and False as false. It returns an error for any other input, including whitespace or mixed casing. Unlike string.bool(), invalid text does not default to false.

Constants #

const single_plus_zero = u32(0x0000_0000)

f32 constants

const single_minus_zero = u32(0x8000_0000)
const single_plus_infinity = u32(0x7F80_0000)
const single_minus_infinity = u32(0xFF80_0000)
const digits = 18

f64 constants

const double_plus_zero = u64(0x0000000000000000)
const double_minus_zero = u64(0x8000000000000000)
const double_plus_infinity = u64(0x7FF0000000000000)
const double_minus_infinity = u64(0xFFF0000000000000)
const c_dpoint = `.`

char constants

const c_plus = `+`
const c_minus = `-`
const c_zero = `0`
const c_nine = `9`
const c_ten = u32(10)

fn add_thousands_sep #

fn add_thousands_sep(s string, sep SeparatorOptions) string

add_thousands_sep inserts sep as a thousands separator into the integer part of the numeric string s. An optional leading sign (- or +) is preserved, and fractional digits are kept unchanged except that their decimal separator is replaced by sep.decimal when sep is a Separator. A string sep uses that string for the integer separator and keeps . as the decimal separator.

Because it operates on an already-formatted string, it composes with any number-to-string conversion: int/i64/u64.str(), f64.str(), strconv.ftoa_*, math.big.Integer.str(), etc.

This function does not do full locale-aware formatting: it groups only the digits before the input decimal point and does not parse or round the value.

Example

assert strconv.add_thousands_sep('1234567', strconv.Separator{}) == '1 234 567'
assert strconv.add_thousands_sep('-1234567.89', strconv.Separator{
	integer: ','
	decimal: ','
}) == '-1,234,567,89'

fn append_quote #

fn append_quote(mut dst []u8, s string)

append_quote appends the result of quote(s) to dst.

fn append_quote_rune #

fn append_quote_rune(mut dst []u8, r rune)

append_quote_rune appends the result of quote_rune(r) to dst.

fn append_quote_rune_to_ascii #

fn append_quote_rune_to_ascii(mut dst []u8, r rune)

append_quote_rune_to_ascii appends the result of quote_rune_to_ascii(r) to dst.

fn append_quote_rune_to_graphic #

fn append_quote_rune_to_graphic(mut dst []u8, r rune)

append_quote_rune_to_graphic appends the result of quote_rune_to_graphic(r) to dst.

fn append_quote_to_ascii #

fn append_quote_to_ascii(mut dst []u8, s string)

append_quote_to_ascii appends the result of quote_to_ascii(s) to dst.

fn append_quote_to_graphic #

fn append_quote_to_graphic(mut dst []u8, s string)

append_quote_to_graphic appends the result of quote_to_graphic(s) to dst.

fn atof64 #

fn atof64(s string, param AtoF64Param) !f64

atof64 parses a decimal string into an f64, including case-insensitive NaN and signed Inf or Infinity. Underscores may separate digits. Whitespace, missing mantissa or exponent digits, and other invalid syntax return errors. A number whose magnitude is too large for an f64 returns a value out of range error. Set allow_overflow to get +inf or -inf for such a number instead. A number too small for an f64 is not an error: it rounds to a subnormal value or to a signed zero. Conversion retains up to 18 significant decimal digits and rounds binary ties to even. Set allow_extra_chars to accept trailing characters after a decimal number.

fn atof_quick #

@[direct_array_access]
fn atof_quick(s string) f64

atof_quick return a f64 number from a string in a quick way

fn atoi #

fn atoi(s string) !int

atoi parses a decimal string into an int, rejecting values outside the i32 range. It follows V scanner as much as observed.

fn atoi16 #

fn atoi16(s string) !i16

atoi16 is equivalent to atoi(s), converted to type i16. returns an i16 [-32678 .. 32767] or an error.

fn atoi32 #

fn atoi32(s string) !i32

atoi32 is equivalent to atoi(s), converted to type i32. returns an i32 [-2147483648 .. 2147483647] or an error.

fn atoi64 #

@[direct_array_access]
fn atoi64(s string) !i64

atoi64 converts radix 10 string to i64 type. returns an i64 [-9223372036854775808 .. 9223372036854775807] or an error.

fn atoi8 #

fn atoi8(s string) !i8

atoi8 is equivalent to atoi(s), converted to type i8. returns an i8 [-128 .. 127] or an error.

fn atou #

fn atou(s string) !u32

atou is equivalent to parse_uint(s, 10, 0), converted to type u32.

fn atou16 #

fn atou16(s string) !u16

atou16 is equivalent to parse_uint(s, 10, 0), converted to type u16. It returns u16 in range [0..65535] or an Error.

fn atou32 #

fn atou32(s string) !u32

atou32 is identical to atou. Here to provide a symmetrical API with atoi/atoi32 It returns u32 in range [0..4294967295] or an Error.

fn atou64 #

fn atou64(s string) !u64

atou64 is equivalent to parse_uint(s, 10, 0), converted to type u64. It returns u64 in range [0..18446744073709551615] or an Error.

fn atou8 #

fn atou8(s string) !u8

atou8 is equivalent to parse_uint(s, 10, 0), converted to type u8. It returns u8 in range [0..255] or an Error.

fn byte_to_lower #

@[inline]
fn byte_to_lower(c u8) u8

fn can_backquote #

fn can_backquote(s string) bool

can_backquote reports whether s can be written unchanged as a Go raw string literal, between backquotes: it holds no control character other than tab, no backquote, no DEL, no invalid UTF-8 and no byte order mark.

fn common_parse_int #

@[direct_array_access]
fn common_parse_int(_s string, base int, _bit_size int, error_on_non_digit bool, error_on_high_digit bool) !i64

common_parse_int parses a signed integer, optionally stopping at invalid digits. It borrows the input string and reports syntax or range errors when requested.

fn common_parse_uint #

fn common_parse_uint(s string, _base int, _bit_size int, error_on_non_digit bool, error_on_high_digit bool) !u64

common_parse_uint is called by parse_uint and allows the parsing to stop on non or invalid digit characters and return with an error

fn common_parse_uint2 #

@[direct_array_access]
fn common_parse_uint2(s string, _base int, _bit_size int) (u64, int)

common_parse_uint2 returns the parsed value as its first result. Its second result is 0 on success, positive for syntax errors (including a non-parseable character's index + 1), -2 for a wrong bit size, or -3 for overflow.

fn dec_digits #

fn dec_digits(n u64) int

dec_digits return the number of decimal digit of an u64

fn f32_to_str #

fn f32_to_str(f f32, n_digit int) string

f32_to_str returns a string in scientific notation with max n_digit after the dot. The digits are the ones of the shortest decimal number that converts back to f, rounded half up when there are more than n_digit of them after the dot. A subnormal f is rounded from its exact value instead, because its shortest digits are too few to be rounded again.

fn f32_to_str_l #

@[manualfree]
fn f32_to_str_l(f f32) string

Todo: Investigate precision issuesf32_to_str_l returns f as a string in decimal notation with a maximum of 8 digits after the dot.

Examples

assert strconv.f32_to_str_l(0.1234567891) == '0.12345679'
assert strconv.f32_to_str_l(34.1234567891) == '34.123455'

fn f32_to_str_l_with_dot #

@[manualfree]
fn f32_to_str_l_with_dot(f f32) string

f32_to_str_l_with_dot returns f as a string in decimal notation with a maximum of 8 digits after the dot. If the decimal digits after the dot are zero, a '.0' is appended for clarity.

Example

assert strconv.f32_to_str_l_with_dot(34.2) == '34.2'

fn f32_to_str_pad #

fn f32_to_str_pad(f f32, n_digit int) string

f32_to_str_pad returns f as a string in scientific notation with n_digit digits after the dot. The digits are the ones of the shortest decimal number that converts back to f: they are rounded half up when there are more than n_digit of them after the dot, and zeros are appended when there are fewer. The result is thus not always the correctly rounded exact value of f, that C's printf("%.*e") prints: f32_to_str_pad(0.1, 10) is 1.0000000000e-01 (and not 1.0000000149e-01), and f32_to_str_pad(9.95, 1) is 1.0e+01 (and not 9.9e+00). A subnormal f is the exception: its shortest digits are too few even for a small n_digit (1e-45 for the smallest one, 1.401298464...e-45), so its exact value is rounded instead.

Examples

assert strconv.f32_to_str_pad(1234.5, 2) == '1.23e+03'
assert strconv.f32_to_str_pad(1.5, 4) == '1.5000e+00'

fn f64_to_str #

fn f64_to_str(f f64, n_digit int) string

f64_to_str returns f as a string in scientific notation with max n_digit digits after the dot. The digits are the ones of the shortest decimal number that converts back to f, rounded half up when there are more than n_digit of them after the dot. A subnormal f is rounded from its exact value instead, because its shortest digits are too few to be rounded again.

fn f64_to_str_l #

@[manualfree]
fn f64_to_str_l(f f64) string

f64_to_str_l returns f as a string in decimal notation with a maximum of 18 digits after the dot.

Example

assert strconv.f64_to_str_l(123.1234567891011121) == '123.12345678910111'

fn f64_to_str_l_with_dot #

@[manualfree]
fn f64_to_str_l_with_dot(f f64) string

f64_to_str_l_with_dot returns f as a string in decimal notation with a maximum of 18 digits after the dot. If the decimal digits after the dot are zero, a '.0' is appended for clarity.

Example

assert strconv.f64_to_str_l_with_dot(34.7) == '34.7'

fn f64_to_str_lnd1 #

fn f64_to_str_lnd1(f f64, dec_digit int) string

f64_to_str_lnd1 formats the exact f64 value with dec_digit fractional digits, rounding half up.

fn f64_to_str_pad #

fn f64_to_str_pad(f f64, n_digit int) string

f64_to_str_pad returns f as a string in scientific notation with n_digit digits after the dot. The digits are the ones of the shortest decimal number that converts back to f: they are rounded half up when there are more than n_digit of them after the dot, and zeros are appended when there are fewer. The result is thus not always the correctly rounded exact value of f, that C's printf("%.*e") prints: f64_to_str_pad(0.1, 20) is 1.00000000000000000000e-01 (and not 1.00000000000000005551e-01), and f64_to_str_pad(9.95, 1) is 1.0e+01 (and not 9.9e+00). A subnormal f is the exception: its shortest digits are too few even for a small n_digit (5e-324 for the smallest one, 4.940656458...e-324), so its exact value is rounded instead.

Examples

assert strconv.f64_to_str_pad(1234.5678, 2) == '1.23e+03'
assert strconv.f64_to_str_pad(1.5, 4) == '1.5000e+00'

fn format_dec_old #

@[manualfree]
fn format_dec_old(d u64, p BF_param) string

max int64 9223372036854775807

fn format_dec_sb #

@[direct_array_access]
fn format_dec_sb(d u64, p BF_param, mut res strings.Builder)

format_dec_sb formats an u64 using a strings.Builder.

fn format_es #

fn format_es(f f64, p BF_param) string

format_es formats the exact f64 value in scientific notation according to p, rounding half up.

fn format_fl #

fn format_fl(f f64, p BF_param) string

format_fl formats the exact f64 value in fixed notation according to p, rounding half up.

fn format_fl_old #

@[direct_array_access; manualfree]
fn format_fl_old(f f64, p BF_param) string

strings.Builder version of format_fl

fn format_int #

@[direct_array_access; manualfree]
fn format_int(n i64, radix int) string

format_int returns the string representation of the number n in base radix Digits with values >= 10 use the lowercase Latin letters a-z.

fn format_str #

@[manualfree]
fn format_str(s string, p BF_param) string

format_str returns the s formatted, according to the options set in p.

fn format_str_sb #

fn format_str_sb(s string, p BF_param, mut sb strings.Builder)

format_str_sb is a strings.Builder version of format_str.

fn format_thousands #

fn format_thousands[T Numeric](number T, sep SeparatorOptions) string

format_thousands returns the base-10 representation of number, inserting a thousands separator every three digits. With a Separator, its integer and decimal fields configure the output; a string uses that string for grouping and . as the decimal separator. T must be one of the types in Numeric; the compiler rejects any other type at the call site, including aliases such as type MyInt = int, which must be cast to their base type.

Example

assert strconv.format_thousands(1234567, strconv.Separator{}) == '1 234 567'
assert strconv.format_thousands(-1234567, strconv.Separator{ integer: ',' }) == '-1,234,567'
assert strconv.format_thousands(1234567.89, strconv.Separator{
	integer: '.'
	decimal: ','
}) == '1.234.567,89'

fn format_uint #

@[direct_array_access; manualfree]
fn format_uint(n u64, radix int) string

format_uint returns the string representation of the number n in base radix for digit values > 10, this function uses the small latin leters a-z.

fn ftoa_32 #

@[inline]
fn ftoa_32(f f32) string

ftoa_32 returns a string in scientific notation with max 8 digits after the dot.

Example

assert strconv.ftoa_32(34.1234567) == '3.4123455e+01'

fn ftoa_64 #

@[inline]
fn ftoa_64(f f64) string

ftoa_64 returns a string in scientific notation with max 17 digits after the dot.

Example

assert strconv.ftoa_64(123.1234567891011121) == '1.2312345678910111e+02'

fn ftoa_long_32 #

@[inline]
fn ftoa_long_32(f f32) string

ftoa_long_32 returns f as a string in decimal notation with a maximum of 8 digits after the dot.

Example

assert strconv.ftoa_long_32(0.1234567901) == '0.12345679'

fn ftoa_long_64 #

@[inline]
fn ftoa_long_64(f f64) string

ftoa_long_64 returns f as a string in decimal notation with a maximum of 17 digits after the dot.

Example

assert strconv.f64_to_str_l(123.1234567891011121) == '123.12345678910111'

fn fxx_to_str_l_parse #

@[direct_array_access; manualfree]
fn fxx_to_str_l_parse(s string) string

fxx_to_str_l_parse returns a string in decimal notation converted from a floating-point string in scientific notation. The special values inf, +inf, -inf, and nan are returned unchanged.

Example

assert strconv.fxx_to_str_l_parse('34.22e+00') == '34.22'

fn fxx_to_str_l_parse_with_dot #

@[direct_array_access; manualfree]
fn fxx_to_str_l_parse_with_dot(s string) string

fxx_to_str_l_parse_with_dot returns a string in decimal notation converted from a floating-point string in scientific notation. The special values inf, +inf, -inf, and nan are returned unchanged. If the decimal digits after the dot are zero, a '.0' is appended for clarity.

Example

assert strconv.fxx_to_str_l_parse_with_dot ('34.e+01') == '340.0'

fn is_graphic #

fn is_graphic(r rune) bool

is_graphic reports whether r is defined as graphic by Unicode: letters, marks, numbers, punctuation, symbols and spaces, from categories L, M, N, P, S and Zs. It differs from is_print only in also accepting the Zs spaces other than U+0020, such as U+00A0 and U+3000.

fn is_print #

fn is_print(r rune) bool

is_print reports whether r is defined as printable by Go, meaning it is in category L, M, N, P, S or the ASCII space.

fn parse_bool #

fn parse_bool(s string) !bool

parse_bool converts these boolean literals: "1", "t", "T", "TRUE", "true", "True" -> true and "0", "f", "F", "FALSE", "false", "False" -> false. Anything else is an error (unlike string.bool(), which defaults to false). It is the V-idiomatic equivalent of Go's strconv.ParseBool.

fn parse_int #

fn parse_int(_s string, base int, _bit_size int) !i64

parse_int interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

If the base argument is 0, the true base is implied by the string's prefix: 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.

fn parse_uint #

fn parse_uint(s string, _base int, _bit_size int) !u64

parse_uint is like parse_int but for unsigned numbers.

fn quote #

fn quote(s string) string

quote returns a double-quoted Go string literal representing s, using Go escape sequences for control characters and the runes is_print rejects. Note that $ is not escaped, so the result is not always a valid V literal.

fn quote_rune #

fn quote_rune(r rune) string

quote_rune returns a single-quoted Go rune literal representing r. An invalid code point is quoted as U+FFFD.

fn quote_rune_to_ascii #

fn quote_rune_to_ascii(r rune) string

quote_rune_to_ascii returns a single-quoted Go rune literal representing r, escaping it if it is not ASCII.

fn quote_rune_to_graphic #

fn quote_rune_to_graphic(r rune) string

quote_rune_to_graphic returns a single-quoted Go rune literal representing r, escaping it if is_graphic rejects it.

fn quote_to_ascii #

fn quote_to_ascii(s string) string

quote_to_ascii returns a double-quoted Go string literal representing s, with every non-ASCII character escaped.

fn quote_to_graphic #

fn quote_to_graphic(s string) string

quote_to_graphic returns a double-quoted Go string literal representing s, escaping only the characters is_graphic rejects.

fn quoted_prefix #

fn quoted_prefix(s string) !string

quoted_prefix returns the quoted literal at the start of s, verbatim and including its quotes. It fails when s does not begin with a valid literal.

fn remove_tail_zeros #

@[direct_array_access]
fn remove_tail_zeros(s string) string

remove_tail_zeros strips trailing zeros from s and return the resulting string.

fn unquote #

fn unquote(s string) !string

unquote returns the string value that s quotes. s may be a Go-syntax single-quoted, double-quoted or backquoted literal; a single-quoted literal yields the one character it holds.

fn unquote_char #

fn unquote_char(s string, quote u8) !UnquoteCharResult

unquote_char decodes the leading character of s, which must be a valid literal body for the given quote byte, and returns the rest of s unchanged. It fails when s does not begin with a decodable character.

quote is the quote byte of the literal s comes from. With ' it accepts the escape \' and rejects an unescaped ', with " likewise for ", and with any other byte, such as 0, it accepts neither escape and both quotes as is.

fn v_printf #

@[unsafe]
fn v_printf(str string, pt ...voidptr)

v_printf prints a sprintf-like formatted string to the terminal. The format string str can be constructed at runtime. Note, that this function is unsafe. In most cases, you are better off using V's string interpolation, when your format string is known at compile time.

fn v_sprintf #

@[direct_array_access; manualfree; unsafe]
fn v_sprintf(str string, pt ...voidptr) string

v_sprintf returns a sprintf-like formatted string. The format string str can be constructed at runtime. Note, that this function is unsafe. In most cases, you are better off using V's string interpolation, when your format string is known at compile time. Small integer and f32 arguments follow C-style default promotions.

Example

x := 3.141516
assert unsafe{strconv.v_sprintf('aaa %G', x)} == 'aaa 3.141516'

fn write_dec #

@[direct_array_access]
fn write_dec(n i64, mut buf []u8) int

write_dec writes the decimal representation of n into buf. It returns the number of bytes written, or -1 if buf is too small.

fn write_dec_u #

@[direct_array_access]
fn write_dec_u(n u64, mut buf []u8) int

write_dec_u writes the decimal representation of n into buf. It returns the number of bytes written, or -1 if buf is too small.

fn Align_text.from #

fn Align_text.from[W](input W) !Align_text

from returns the Align_text value of an integer or of a field name, or an error if there is none.

fn (Dec32) get_string_32 #

@[direct_array_access; manualfree]
fn (d Dec32) get_string_32(neg bool, i_n_digit int, i_pad_digit int) string

max 46 char -3.40282346638528859811704183484516925440e+38

type Numeric #

type Numeric = int | i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | isize | usize | f32 | f64

Numeric is the set of built-in numeric types accepted by format_thousands: int, i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32 and f64. Generic code that forwards a T to it can use [T strconv.Numeric] as its constraint.

type SeparatorOptions #

type SeparatorOptions = string | Separator

enum Align_text #

enum Align_text {
	right = 0
	left
	center
}

Align_text is used to describe the different ways to align a text - left, right and center

struct AtoF64Param #

@[params]
struct AtoF64Param {
pub:
	allow_extra_chars bool // allow extra characters after number
	allow_overflow    bool // allow numbers too large for an f64, returning +inf or -inf for them
}

struct BF_param #

struct BF_param {
pub mut:
	pad_ch       u8   = u8(` `) // padding char
	len0         int  = -1      // default len for whole the number or string
	len1         int  = 6       // number of decimal digits, if needed
	positive     bool = true    // mandatory: the sign of the number passed
	sign_flag    bool // flag for print sign as prefix in padding
	align        Align_text = .right // alignment of the string
	rm_tail_zero bool // remove the tail zeros from floats
}

BF_param is used for describing the formatting options for a single interpolated value

struct Float32u #

union Float32u {
pub mut:
	f f32
	u u32
}

struct Float64u #

union Float64u {
pub mut:
	f f64
	u u64
}

struct PrepNumber #

struct PrepNumber {
pub mut:
	negative bool // 0 if positive number, 1 if negative
	exponent int  // power of 10 exponent
	mantissa u64  // integer mantissa
}

The structure is filled by parser, then given to converter.

struct Separator #

struct Separator {
pub:
	// integer is inserted every three digits in the integer part.
	integer string = ' '
	// decimal separates the integer and fractional parts.
	decimal string = '.'
}

Separator configures the separators used by numeric formatting functions. integer is inserted every three digits in the integer part, while decimal replaces the decimal point before the fractional part. An empty decimal keeps the default . decimal point.

struct UnquoteCharResult #

struct UnquoteCharResult {
pub:
	value     rune
	multibyte bool
	tail      string
}

UnquoteCharResult is the result of unquote_char: the rune that was decoded, whether it was written as a multi-byte sequence, and whatever followed it.