Float Literals
Plain
Any valid integer constant shown in
the previous section is also a valid float
constant and can be passed to a value of a float type like f64
.
Fractions
Unlike integers, floats may be fractions.
Exponents
Exponents to base ten can be added using E
, to base two
using P
, followed by an optional sign +
or -
and the exponent values.
Overflows
Values that do not fit into the type they are assigned to will cause a compile time error:
Underflows
An underflow, i.e., a value that is so small that it would be rounded to zero, is considered an error:
Bases
Just like integer constants, float constants can be given in decimal, binary,
octal or hexadecimal representation. A
prefix 0d
, 0b
, 0o
or 0x
,
respectively, selects the base to be used. If no prefix is given, decimal
representation using base 10 is used as default. The base can be selected
individually for the significand and for the exponent:
Types
The type of a float literal that is assigned to a field is inferred from that field. If the field, however, has itself a type that is inferred from the value assigned to it, the type of the float literal is f64. To distinguish floats from integers, a decimal point is required in this case, even if the float literal represents an integer.
When performing calculations with float literals using infix operators, the type of the calculation depends on the left operand:
To explicitly choose a type for a literal, you place the name of the type in
front of it as in f32 1
:
When adding the type explicitly before the float literal, you actually call
the constructor of that type giving the constant as an argument. All built-in
numeric types have a constructor with one argument val
that has the
same type. Consequently, the type inference mechanism forces that type onto the
constant.