Rust, Software Development

Rust – Convert Integer to String Or Format Numeric Values

We can use the Rust functions to_string(), and format functions to format or convert integer values to string values. This post shows how to use these functions on each of Rust’s integer types.

Rust Integer Types

There are six (6) integer types in Rust. These are i8/ u8 , i16/ u16, i32/ u32 , i64/ u64 , and isize/ usize .

Convert i8 and u8 Integers to String

The integer types i8 and u8 are 8-bit signed and unsigned storage, respectively.

The codes generate the following output.

Convert i16 and u16 Integers to String

Next, we have i16/u16 integers. These numeric types are 16-bit values – signed or unsigned.

When we run the codes, we get the following result.

Convert i32 and u32 Integers to String

First, we try out i32/ u32 types. These integer values are 32-bit values and are either signed or unsigned.

We will get the following result when we run the codes.

Convert i64 and u64 Integers to String

Most other programming languages can handle 64-bit values, and we know them mostly as long values. In Rust, we have the equivalent type – the i62/u64 types, which are 64-bit values.

The codes generate the following output.

Convert i128 and u128 to String

Then, we have 128-bit integer types – these are i128/ u128.

The codes:

Convert Rust isize and usize Integer to String

Lastly, we have the isize/ usize integer values. These are N-bit values – signed or unsigned. Moreover, these types depend on the computer the program is running on 64 bits for 64-bit architecture and 32 bits for 32-bit architecture machines.

Output:

Although not integer types, Rust has f32 and f64 types for floating-point numbers. We could use the same way of converting these values to String in Rust. Consider the following codes.

If we don’t specify the floating-point type, Rust assumes the value is of type f64.

Tested with Rust 1.53.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like