---
title: "parse_int"
url: https://una-lang.org/en/docs/std/prelude/parse_int/
release: v0.4.0
edition: "0.2 and later"
source: https://github.com/una-lang/una/blob/v0.4.0/docs/std/listing.json
---

# parse_int

A function of the prelude, in scope in every module. Edition 0.2 and later.

```una
pub parse_int(t: Text) -> Int
  fails ParseError
```

The integer that `t` writes, an optional `-` and one or more ASCII digits (`spec/22 §4`).

## Parameters

- `t`: the text

## Returns

`Int`: the integer `t` writes\, an optional `-` and one or more ASCII digits\; space is not trimmed.

## Fails with

- `Empty` when `t` is empty
- `NotADigit` when a character is neither the leading `-` nor an ASCII digit\; `at` is the scalar position\, from 0\, of the first one
- `NoDigits` when `t` is `-` alone
- `TooLong` when `t` is an optional `-` and more than 4300 ASCII digits\, leading zeros included

## Use instead

- [`to_int`](https://una-lang.org/en/docs/std/prelude/to_int/) when the reason does not matter

## See also

[`ParseError`](https://una-lang.org/en/docs/std/prelude/ParseError/), [`trim`](https://una-lang.org/en/docs/std/prelude/trim/), [`is_digits`](https://una-lang.org/en/docs/std/prelude/is_digits/)

## Cost

Time `O(b)` (ADR 0070), where:

- `b`: the length of `t` in UTF\-8 bytes

## Example

`src/shop.una`

```una
module shop

--- A stock adjustment typed by hand, and why it is not one. A sign is allowed, so `-3`
--- writes off three units.
adjustment(raw: Text) -> Text
=
  let outcome = attempt parse_int(raw)
  when outcome
    is Ok(n) -> "'{raw}': adjust the stock by {n}"
    is Err(failure) -> "'{raw}': {reason(failure)}"

reason(failure: ParseError) -> Text
=
  when failure
    is Empty -> "nothing typed"
    is NoDigits -> "a sign and no digits"
    is NotADigit(at) -> "not a digit at {at}"
    is TooLong -> "more digits than an integer may have"

pub main() -> Unit
  uses @console: Console[print]
=
  @console.print(adjustment("12"))
  @console.print(adjustment("-3"))
  @console.print(adjustment(""))
  @console.print(adjustment("-"))
  @console.print(adjustment("1x2"))
```

`una run .` prints:

```text
'12': adjust the stock by 12
'-3': adjust the stock by -3
'': nothing typed
'-': a sign and no digits
'1x2': not a digit at 1
```

## Specification

- [`spec/22 §4`](https://una-lang.org/en/docs/spec/22-text/#s4)

Generated from the standard modules of una v0.4.0 ([`docs/std/listing.json`](https://github.com/una-lang/una/blob/5fec93d88932b333feec25e589355a2cb34c37b5/docs/std/listing.json), which is not part of the specification). The specification governs: [`spec/14 §1`](https://una-lang.org/en/docs/spec/14-standard-library/#s1).
