How to Convert Float to String in R

Here are three ways to convert a float to a string in R:

  1. Using as.character()
  2. Using sprintf()
  3. Using toString()

Method 1: Using as.character()

The as.character() function generates a string representation of a provided argument.

Method 1 - Using as.character()

float_val <- 21.19

chr <- as.character(float_val)

chr

Output

[1] "21.19"

To check the variable data type, use the typeof() function.

float_val <- 21.19

chr <- as.character(float_val)

typeof(chr)

Output

[1] "character"

Method 2: Using sprintf()

To convert without losing precision, use the “sprintf()” function.

Method 3 - Using the sprintf() function

float_val <- 21.19000

chr <- sprintf("%0.5f", float_val)

print(chr)

print(typeof(chr))

Output

[1] "21.19000"

[1] "character"

Method 3: Using toString()

The toString() function returns a single character string describing an R object. It converts an object to a character type.

Method 2 - Using the toString() method

float_val <- 21.19

chr <- toString(float_val)

print(chr)

print(typeof(chr))

Output

[1] "21.19"

[1] "character"

That’s it!

Leave a Comment