This tutorial explains about conversion of different types.

How to convert Integer to Float in NIm

Nim System module provides a toFloat method that converts int to float type.

Syntax:

toFloat(int): float

Output

echo toFloat(10) # 10.0

It throws an exception if the number contains non-numeric characters.

echo toFloat(10f) # Error

Output:

/home/runner/FilthyNecessaryInstances/main.nim(1, 13) Error: type mismatch: got but expected one of: proc toFloat(i: int): float first type mismatch at position: 1 required type for i: int but expression ‘10.0’f32’ is of type: float32

expression: toFloat(10.0’f32) exit status 1

How to convert Float to Integer in NIm

Nim System module provides a toInt method that converts float to int type. It rounds the floating decimal value to the nearest integer and returns an int value.

Syntax:

toInt(float): int

Output

echo toInt(11.78) # 12.0
echo toInt(11.12) # 11.0
echo toInt(11.50) # 12.0

It throws an Error: invalid number: '11.78ad' if the number contains non-numeric characters.

echo toInt(11.78ad) # Error

How to convert Integer to String

Following Multiple ways we can convert Int to String In NIm

  • using the $ symbol

using $ symbol number type assigned to string variable using the $ symbol.

let number = 5
let str = $number
echo str
echo typeOf(str)

Output:

5
string
  • use strutils intToStr function

strutils intToStr function converts int to string with default minchars parameter. Syntax:

func intToStr(x: int; minchars: Positive = 1): string {.....}

example

import strutils

let number = 5
let str = intToStr(number)
echo str
echo typeOf(str)

How to convert string to Integer in Nim

import strutils

let str = "5"
let number = parseInt(str)
echo number
echo typeOf(number)

Output:

5
int

if the string contains non-numeric characters, It throws “Error: unhandled exception: invalid integer: 5abc [ValueError]`.

We can use the exception handle using try, except

import strutils

let str = "5abc"
try:
  let number = parseInt(str)
  echo number
  echo typeOf(number)
except ValueError as e:
  echo "Not able to convert"

Output:

Not able to convert

How to convert int to/from a character in Nim

chr(int) converts int to Character. ord(character) converts a character to an integer Here is an example

echo chr(65) # A
echo chr(66) # B

echo ord('A') # 65
echo ord('B') # 66

How to check whether two types are equal or not

There are two operators.

  • is checks the given variable is type, and returns true if the matched type
  • isnot checks given variable is not type, returns true if not matched type

Here is an example

let number=1
let number1=1

let str="abc"

echo number is int # true
echo number1 isnot string # true
echo str is string # true