Number
| Description: | When used in a type annotation or signature, matches either an int or a float. |
| Annotation: | number |
| Literal syntax: | N/A - Any int or float literal can be assigned to a number |
| Casts: | N/A |
Additional Language Notes
numberis a type for annotations, likeany. No single value has the typenumber. A value annotated asnumberkeeps its own type, sodescribereportsintorfloat:def kind [x: number] { $x | describe } [(kind 1) (kind 1.5)] | to nuon # => [int, float]describeshowsnumberonly for a collection that mixes ints and floats:[1 2.5] | describe # => list<number>Other types are rejected, including text that looks like a number and the number-like
filesizeanddurationtypes. A literal is checked when the code is parsed:let n: number = "1" # => Error: nu::parser::type_mismatch # => # => × Type mismatch. # => ╭─[repl_entry #1:1:17] # => 1 │ let n: number = "1" # => · ─┬─ # => · ╰── expected number, found string # => ╰────Convert text with
into intorinto floatfirst.A
mutvariable without an annotation keeps the type of its first value, so an int variable can't later hold a float. Annotate it asnumberto allow both:mut total: number = 0 $total = $total + 2.5 $total # => 2.5Without the annotation,
$total = 2.5aftermut total = 0fails withnu::parser::operator_incompatible_types.numberalso works as an input or output type, and inside other types such aslist<number>:def half []: number -> float { $in / 2 } [(4 | half) (1.5 | half)] | to nuon # => [2.0, 0.75]Many built-in commands use it this way.
help math abs, for example, listsnumberandlist<number>among its input types.A
numbercan be passed where anintor afloatis expected. The parser lets it through, and the value is checked when the command runs. See Which values a type accepts.