In this article, we will take a look at 4 different ways to convert a float value to string in python with examples.
str()
is a built in python function to convert a float to string.It accepts the float value to be converted as argument and returns the corresponding string value. Example,
float_val = 123.45 string_val = str(float_val) print(type(string_val)) // prints <class 'str'>
2. f-strings
f-strings also called Formatted string literals, begin with f
or F
followed by quotations(‘ or “”).
Between these quotations, you can write expressions which can be variables between curly braces. Example,
float_val = 123.45 string_val = f"{float_val}" print(type(string_val)) // prints <class 'str'>
The return value of f-string is a string.
You can also format variables with f-strings.
So, to convert a float value to a string with 2 decimal places, you can use below
float_val = 123.456 string_val = f"{float_val:.2f}" print(string_val) // prints 123.46 print(type(string_val)) // prints <class 'str'>
Note that f-strings are added in python 3.6.
format()
is a function of str
class in python.It is called on a string. This string can be a value or a format.
When converting a float to string, you need to provide a format enclosed in quotes and curly braces followed by format()
and the value as argument.
It returns the formatted value as a string. Example,
float_val = 123.45 string_val = "{:.2f}".format(float_val) print(type(string_val)) // class <'str'>
In the above example, .2f
is the format to convert a float to 2 decimal places.
4. Modulus operator
Python modulus operator(%
) can also be used to convert and format a float to a string.
Its syntax is
‘string’ % value
where string can be a format containing % symbol followed by a format.
The % symbol of the string is replaced with the value and then format is applied over it resulting in a string. Example,
float_val = 123.4567 string_val = "%.3f" % float_val print(string_val) // 123.457 print(type(string_val)) // <class 'str'>
Above example converts the float value to 3 decimal places(due to .3f
).
Note that the % in %.3f
is replaced with the float value first.
That is all on converting a float value to string in python.
Hope the article was useful.