Rust, Software Development

Rust – Convert Integer to String Or Format Numeric Values

Rust key value hashmap map convert integer string check NULL value Connect postgreSQL

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 [crayon-616b1a3a5d5c8751534517-i/] and [crayon-616b1a3a5d5c9570086517-i/] Integers to String

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

The codes generate the following output.

Convert [crayon-616b1a3a5d5ce551579407-i/] and [crayon-616b1a3a5d5cf950566144-i/] 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 [crayon-616b1a3a5d5d4744592228-i/] and [crayon-616b1a3a5d5d5111575341-i/] 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 [crayon-616b1a3a5d5dc747186327-i/] and [crayon-616b1a3a5d5dd407531862-i/] 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 [crayon-616b1a3a5d5e2345012980-i/] and [crayon-616b1a3a5d5e3208891891-i/] to String

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

The codes:

Convert Rust [crayon-616b1a3a5d5ea502422691-i/] and [crayon-616b1a3a5d5eb608349568-i/] 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.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like