unsafe_trunc

unsafe_trunc(T, x)

unsafe_trunc(T, x) returns the nearest integral value of type T whose absolute value is less than or equal to x. If the value is not representable by T, an arbitrary value will be returned.

Examples

  1. Truncate a floating-point number to an integer:

    julia> unsafe_trunc(Int, 3.8)
    3

    This example truncates the floating-point number 3.8 to an Int, resulting in the value 3.

  2. Convert a float to an unsigned integer:

    julia> unsafe_trunc(UInt8, -2.5)
    254

    It converts the floating-point number -2.5 to a UInt8 by truncating the decimal part and returning the nearest integral value.

  3. Handle cases where the value is not representable:
    julia> unsafe_trunc(UInt8, 300.7)
    44

    In this example, the value 300.7 is not representable as a UInt8, so an arbitrary value is returned, in this case, 44.

Common mistake example:

julia> unsafe_trunc(Int8, 200)
-56

Here, the value 200 is not representable as an Int8 because it exceeds the range of representable values. The function returns an arbitrary value, which in this case is -56. It is important to ensure that the target type T can represent the value x before using unsafe_trunc.

See Also

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: