Skip to content

Number Conversion

Spice
import "std/type/number-conversion";

Functions

parseIntegerText

Spice
public f<long> parseIntegerText(string input, int base)

Parse the longest prefix of the input, that is an integer in the given base, like strtoll. Leading whitespace and a sign are allowed. Base 16 allows a 0x prefix and base 0 detects the base from the prefix (0x: 16, 0: 8, else 10). A value out of the range of long is clamped to the range.

Parameters

Name Type Description
input string Input text
base int Base from 2 to 36 or 0

Returns: long — Parsed value or 0, if the input starts with no integer or the base is invalid

parseDoubleText

Spice
public f<double> parseDoubleText(string input)

Parse the longest prefix of the input, that is a floating point number, like strtod. Leading whitespace and a sign are allowed. Besides decimal numbers like 1.5e-3, hexadecimal ones like 0x1.8p3, inf, infinity and nan are accepted, ignoring the case. The result is rounded exactly to the nearest double, ties to even.

Parameters

Name Type Description
input string Input text

Returns: double — Parsed value or 0, if the input starts with no number

formatUnsignedInteger

Spice
public f<String> formatUnsignedInteger(unsigned long value)

Format an unsigned integer in decimal, like "%llu"

Parameters

Name Type Description
value unsigned long Value

Returns: String — Decimal text

formatSignedInteger

Spice
public f<String> formatSignedInteger(long value)

Format a signed integer in decimal, like "%lld"

Parameters

Name Type Description
value long Value

Returns: String — Decimal text

formatFixedDouble

Spice
public f<String> formatFixedDouble(double value, int precision)

Format a double with a fixed number of decimal places, like "%.*f". The value is rounded exactly, ties to even.

Parameters

Name Type Description
value double Value
precision int Number of decimal places. A negative one means 6, like in C

Returns: String — Formatted text

formatSignificantDouble

Spice
public f<String> formatSignificantDouble(double value, int significantDigits)

Format a double with the given number of significant digits, like "%.*g": in exponential notation (1.5e+20) for exponents below -4 or from the number of digits on, in decimal notation otherwise, without trailing zeros. The value is rounded exactly, ties to even. 17 digits are enough to read back the same double.

Parameters

Name Type Description
value double Value
significantDigits int Number of significant digits, from 1 to 17. Other values are clamped to this range

Returns: String — Formatted text