Skip to main content
Log in

Mojo trait

FloatableRaising

The FloatableRaising trait describes a type that can be converted to a Float, but the conversion might raise an error (e.g.: a string).

Any type that conforms to FloatableRaising works with the built-in float function.

This trait requires the type to implement the __float__() method, which can raise an error.

For example:

from utils import Variant

@value
struct MaybeFloat(FloatableRaising):
var value: Variant[Float64, NoneType]

fn __float__(self) raises -> Float64:
if self.value.isa[NoneType]():
raise "Float expected"
return self.value[Float64]
from utils import Variant

@value
struct MaybeFloat(FloatableRaising):
var value: Variant[Float64, NoneType]

fn __float__(self) raises -> Float64:
if self.value.isa[NoneType]():
raise "Float expected"
return self.value[Float64]

A MaybeFloat can now be converted to Float64 using float:

try:
print(float(MaybeFloat(4.6)))
except:
print("error occured")
try:
print(float(MaybeFloat(4.6)))
except:
print("error occured")

Implemented traits

AnyType, UnknownDestructibility

Methods

__float__

__float__(self: _Self) -> SIMD[float64, 1]

Get the float point representation of the value.

Returns:

The float point representation of the value.

Raises:

If the type does not have a float point representation.