How to Convert Float to String in R Language

To define a string in R, wrap the text in either single or double quotes, and it will become a string.

Converting one format to another format is a common task, and we saw how to convert string to float in R in this blog. Now let’s see the reverse process means converting a float value to a string value.

There are two ways that can convert a float to string in R.

  1. Using as.character() function
  2. Using toString() function

Let’s see these functions one by one.

Convert Float to String in R

To convert float to String in R, use the as.character() function. The as.character() a built-in function in R that generates a string representation of a provided argument. The as.character() method takes an R object as an argument and tries to coerce to the string format.

Pass the float argument to the as.character() function, and it returns the string version of the float argument.

ft <- 21.19
chrt <- as.character(ft)
chrt

Output

[1] "21.19"

And we get the string from the float using the as.character() function.

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

ft <- 21.19
chrt <- as.character(ft)
typeof(chrt)

Output

[1] "character"

We can see that we got the character in the output since there is no built-in string data type.

Using the toString() method to convert float to String

The toString() is a built-in R function that produces a single character string describing an R object. The toString() function converts an object to a character type.

To convert a float value to a string or character type, use the toString() function.

ft <- 21.19
chrt <- toString(ft)
print(chrt)
print(typeof(chrt))

Output

[1] "21.19"
[1] "character"

And we get the string or character type in the output.

Convert float to string in R without losing precision

To convert float to string value without losing precision in R, use the sprintf() function.

ft <- 21.19000
chrt <- sprintf("%0.5f", ft)
print(chrt)
print(typeof(chrt))

Output

[1] "21.19000"
[1] "character"

Here, you can see that output does not lose the float value’s precision. The input float value is 21.19000. So hereafter the floating-point, there are five numeric values(19000), and to retain those values, we are using the sprintf() function and pass the “0.5f,” which means that it will retain up to five values after the floating point when converting to a string.

That is it for converting float to String in R tutorial.

Leave a Comment