# Casting
source: https://docs.chalk.ai/docs/chalkdf/expressions/casting

## Convert input values, identify failed conversions, and preserve identifiers.

Choose a type from the meaning of the field. An amount encoded as text needs conversion for arithmetic. A numeric-looking account identifier often needs to keep its spelling. Keep the raw field while validating a new feed.

### Convert text to a number

Add a parsed column and inspect it beside the source.

```python
from chalk import _, functions as F
from chalkdf import DataFrame

tx = DataFrame({
    "account": ["001", "002", "003", "004", "005"],
    "raw": ["12", "0", "", "unknown", None],
})

parsed = tx.with_columns(_.raw.cast(int).alias("amount"))
parsed.run()
```

| account · `string` | raw · `string` | amount · `int64` |
| ------------------ | -------------- | ---------------- |
| 001                | 12             | 12               |
| 002                | 0              | 0                |
| 003                |                | null             |
| 004                | unknown        | null             |
| 005                | null           | null             |

For these string-to-integer conversions, the empty string and the malformed value produce null. The valid string "0" becomes zero. The original null remains null.

### Find failed conversions

A null result alone cannot tell you whether the input was absent or malformed. Select rows where a value was supplied but parsing returned null.

```python
parsed.filter(F.is_not_null(_.raw) & F.is_null(_.amount)).select("account", "raw").run()
```

| account · `string` | raw · `string` |
| ------------------ | -------------- |
| 003                |                |
| 004                | unknown        |

This gives you the two records to investigate while leaving genuinely missing source values out of the error count.

### Choose precision before arithmetic

Casting these floating-point amounts to integers rounds them to the nearest integer. Compare representations before selecting a storage type for amounts.

```python
values = DataFrame({"amount": [12.75, -3.5, 0.0]})
values.project({
    "original": _.amount,
    "integer": _.amount.cast(int),
    "rounded": F.round(_.amount, 0),
}).run()
```

| original · `double` | integer · `int64` | rounded · `double` |
| ------------------- | ----------------- | ------------------ |
| 12.75               | 13                | 13.0               |
| -3.5                | -4                | -4.0               |
| 0.0                 | 0                 | 0.0                |

The result types differ: the cast produces integers and rounding retains floating-point values. If the downstream field represents cents, establish the scale and rounding convention before converting.

### Preserve identifiers across a conversion

Cast the parsed amount back to text for a display field and keep the original account ID as its own column.

```python
parsed.filter(F.is_not_null(_.amount)).project({
    "account": _.account,
    "display_amount": _.amount.cast(str),
}).run()
```

| account · `string` | display_amount · `large_string` |
| ------------------ | ------------------------------- |
| 001                | 12                              |
| 002                | 0                               |

An integer representation of the account would lose its leading zeros. Converting it back to a string would give a different join key.

### Parse timestamps before comparing them

Two timestamps with different offsets can represent the same instant. Parse their ISO 8601 text so comparisons use time values.

```python
events = DataFrame({"stamp": ["2025-01-01T12:00:00Z", "2025-01-01T07:00:00-05:00"]})
events.project({
    "source": _.stamp,
    "is_noon_utc": F.from_iso8601_timestamp(_.stamp) == F.from_iso8601_timestamp("2025-01-01T12:00:00Z"),
}).run()
```

| source · `string`         | is_noon_utc · `bool` |
| ------------------------- | -------------------- |
| 2025-01-01T12:00:00Z      | True                 |
| 2025-01-01T07:00:00-05:00 | True                 |

Keep the source field if the offset as originally written matters. Both parsed rows represent noon UTC.

### Check the range before narrowing an integer

Inspect values at the boundary when a downstream schema requires fewer bits. Use an explicit Arrow type for the destination.

```python
import pyarrow as pa

counts = DataFrame({"raw": [0, 127, 128]})
counts.project({"raw": _.raw, "narrow": _.raw.cast(pa.int8())}).run()
```

| raw · `int64` | narrow · `int8` |
| ------------- | --------------- |
| 0             | 0               |
| 127           | 127             |
| 128           | null            |

A signed eight-bit integer holds values from -128 through 127. Keep the original field while checking the conversion.

See [missing data](/docs/chalkdf/expressions/missing-data) and [DataFrame.project](/dataframe-docs#DataFrame.project).





