Select Page

# How to Get an Absolute Value in Rust

We can calculate the absolute value of a number using the `abs()` method. We have to specify the numeric type before we call the abs method, for example, if we want a 32-bit signed integer we need to put i32 after the number.

This tutorial will go through how to calculate the absolute value of a numeric value in Rust with code examples.

## Example #1: Absolute Value of a Signed Integer

Let’s look at an example where we want to calculate the absolute value of an integer:

```fn main() {
let num = -4
let abs_num = num.abs();
println!("{}", abs_num);
}```

In the above code, we define the number and then call the abs() method. Let’s run the code to see what happens:

```error[E0689]: can't call method `abs` on ambiguous numeric type `{integer}`
--> src/main.rs:3:23
|
3 |     let abs_num = num.abs();
|                       ^^^
|
help: you must specify a type for this binding, like `i32`
|
2 |     let num: i32 = -4;
|         ~~~~~~~~```

The error occurs because we did not define the specific numeric type. We need to put an i32 after the number so that Rust knows the number is a 32-bit signed integer. Let’s look at the revised code:

```fn main() {
let num = -4i32
let abs_num = num.abs();
println!("{}", abs_num);
}```

Let’s run the code to see the result:

`4`

We successfully calculated the absolute value of -4, which is 4

The absolute method abs() is an available method for most numeric types.

## Example #2: Absolute Value of a Signed Float

Let’s look at an example where we want to calculate the absolute value of a floating point. We need to put an f32 after the number so that Rust knows the number is a 32-bit signed float.

```fn main() {

let num = -3.4f32;

let abs_num = num.abs();

println!("{}", abs_num);

}```

Let’s run the code to see the result:

`3.4`

We successfully calculated the absolute value of -3.4, which is 3.4.

## Summary

Congratulations on reading to the end of this tutorial! For further reading on Rust, go to the articles:

Have fun and happy researching!