# 12.3 Conversions

> Conversions change a value's type explicitly: from number to text, from text to number, or from real to text with a fixed number of decimals.

Web page: https://pseudolearn.app/en/spec/biblioteca/conversion

> **In one sentence**
>
> Conversions change a value's type explicitly: from number to text, from text to number, or from real to text with a fixed number of decimals.

## 12.3.1 How it works

PseudoLearn never converts on its own. When needed, you ask:

| Function | Converts |
| --- | --- |
| `toText(v)` | any primitive to `String`, with the same format as `Write` |
| `toInteger(t)` | a decimal string to `Integer` |
| `toReal(t)` | a decimal string to `Real` |
| `decimals(x, n)` | a number to text with exactly `n` decimals |

**Figure 12.3-1: Back and forth between text and number**

At the top, the text "42" becomes a number with toInteger and comes back with toText. Below, the text "doce" cannot be converted and toInteger fails.

Conversions go back and forth between text and numbers. If the text is not a number, the conversion fails instead of making up a zero.

### Program: Converting both ways

```pseudolearn
Algorithm Conversiones
  Write toText(12) + "!", " ", toInteger("42") + 1, " ", toReal("2.5") * 2;
  Write decimals(3.14159, 2), " ", decimals(2.5, 0), " ", decimals(-0.001, 1);
EndAlgorithm
```

**Output**

```text
12! 43 5.0
3.14 3 -0.0
```

*The program finishes normally.*

`decimals` rounds ties away from zero, keeps the sign —that is why `-0.001` with one decimal is `-0.0`— and uses no thousands separators.

> **Common mistakes**
>
> ### Program: A text that is not a number
>
> ```pseudolearn
> Algorithm Mal
>   Write toInteger("doce");
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `stringToNumberConversionFailed` (error, 2:9): Text doce does not represent a number
>
> *The program finishes with an error.*

**In short**
- Every conversion is explicit.
- `toText`, `toInteger` and `toReal` go between text and numbers.
- A text that is not a number fails; it does not become zero.
- `decimals` fixes a number's decimals.

**See also**
- [4.6 Concatenation](https://pseudolearn.app/en/spec/expresiones/concatenacion.md)
- [3.1 Primitive types](https://pseudolearn.app/en/spec/tipos/primitivos.md)
