In this tutorial we’ll learn about different ways that we can use to convert one or multiple float numbers to string objects in Python.
Convert a floating number to string
In order to cast a single float number into a string you can use the Python str function:
#Python3 # strat by defining a float number fl_val = 97.1111 # cast float to string str_val = str(fl_val) print ('The workshop attendance rate was ' +str_val +'%.')
This will return:
The workshop attendance rate was 97.1111%.
Float to string with rounding
If we would like to get rid of the decimals, we can round the float first:
fl_val = 97.1111 # round the float number str_val = str(round(fl_val)) print ('The workshop attendance rate was ' +str_val +'%.')
And here is our result:
The workshop attendance rate was 97%.
Rounding with 2 decimal precision and converting to string
We can round up values with specific precision using the round() Python function.
fl_val = 97.1111 str_val = str(round(fl_val,2)) print ('The workshop attendance rate was ' +str_val +'%.')
The result will be:
The workshop attendance rate was 97.11%.
Convert a list of floats to strings
The methods outlined below need to be slightly adjusted to handle a list object populated with floats:
#list of floating numbers fl_lst = [98.2, 97.4, 95.111] # use a list comprehension to round and cast to string str_lst = [str(round(x,1)) for x in fl_lst] #print the list of strings print(str_lst)
And here is the result:
['98.2', '97.4', '95.1']
Convert float Pandas Series to strings
You can also perform similar manipulations on a Pandas Series (DataFrame column).
# import pandas import pandas as pd fl_lst = [98.2, 97.4, 95.111] # define list of floats fl_s = pd.Series(fl_lst) #export to string fl_s.to_string(index=False)
Numpy array of floats to strings
# import the numpy library import numpy as np fl_lst = [98.2, 97.4, 95.111] # define numpy array from list fl_arr = np.array(fl_lst) #convert float array to strings fl_arr.astype(str)
Here is the resulting array of strings:
array(['98.2', '97.4', '95.111'], dtype='<U32')