Reference · General
float
signature
float(any) -> float | error(str)What it does
The value as a float. Text is parsed (a sign, digits, a point, an exponent, with spaces
around them allowed); an int or a decimal becomes the nearest float; a float is itself.
What cannot be a float is an error value, not a runtime error, so the result can be
checked with is_err or given a default with ??.
Examples
print(float("3.5"), float(" 2 "), float("1e3"), float("+2.5"))print(float(3), float(dec("1.25")), float(1.5))output
3.5 2.0 1000.0 2.53.0 1.25 1.5Edge cases
nan,infand-infare read as text:float("nan")isNaN, a float, not an error.- Only ASCII digits and a point: a comma, a
_between digits, hex ("0x10"), binary ("0b11"), octal ("0o17") and digits in other scripts are errors, in the browser too. - The empty string and
nullare errors, not0.0: give the default with??. - A boolean is an error too, unlike
int(true), which is 1. float(1)is1.0, withtype_offloat, in the browser too: a whole float stays a float there, so2.0 / 0isinfand anintparameter refuses2.0.
print(float("nan"), float("inf"), float("-inf"))print(float("3,5"), float("1_000"), float("0x10"))print(float(""), float(null), float(true))print(float(null) ?? 0.0, type_of(float(1)))output
NaN inf -inferr("not a number: \"3,5\"") err("not a number: \"1_000\"") err("not a number: \"0x10\"")err("not a number: \"\"") err("cannot convert null to float") err("cannot convert bool to float")0.0 floatErrors
The error value says what was given. is_err sees it, ? passes it on, ?? replaces
it. A page that needs an int from text uses int instead.
let x = float("x")print(is_err(x), x.error, x ?? 0.0)output
true not a number: "x" 0.0Chaining
print("1.5,2.5" | split(",") | map(float) | sum)print(["1", "x", "2.5"] | map(float) | filter((v) => !is_err(v)))output
4.0[1.0, 2.5]See also
Thread
Thread 0 posts
On float(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo