NumPy Data Types and Casting
astype converts values to another dtype. Some conversions lose fractions, overflow a range or reject text, so decide which losses are allowed.
How it works
Converting a floating measurement to an integer truncates its fractional part toward zero; it does not perform the same operation as rounding to the nearest unit. A narrow integer type also has finite limits. Inspect np.iinfo or np.finfo when the representable range matters. Casting policy and input validation belong at the boundary, especially when a calculation will combine data from several sources.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python dtype-casting.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
values = np.array([2.9, -2.9], dtype=np.float64)
print(values.astype(np.int64).tolist())
print(np.rint(values).astype(np.int64).tolist())
print(np.iinfo(np.int16).max)
Expected result
[2, -2] [3, -3] 32767
Truncation and rounding answer different questions, so their results intentionally differ. The integer limit is a property of the chosen representation, not a maximum quantity the application should necessarily accept.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.