Python Float to String [Explained with Code Examples] - JSON Viewer

Python Float to String [Explained with Code Examples]

Introduction

A float is a numeric data type that represents numbers with decimal points or fractional parts. A string, on the other hand, is a sequence of characters.

Converting a float to a string in Python means converting a floating-point number to a string representation of that number. This can be done using the str() function or the format() method. Let’s look at each method in detail.

Different Methods to Convert Python Float to String

1. Using the str() function

The str() function is a built-in Python function that can be used to convert values of various data types to strings, including floats.

Example:

#Float to String using str() function
float_num = 3.14159
str_num = str(float_num)
print(str_num)

Output:

'3.14159'

In the example above, the float_num variable holds a float value, and the str() function is used to convert it to a string representation, which is then stored in the str_num variable. The resulting string ‘3.14159’ represents the float value 3.14159 as a string.

2. Using the format() method

The format() method is a string method in Python that allows you to format strings by substituting values into placeholders. You can use it to convert a float to a string with specific formatting options.

Example:

# Float to String using format() method
float_num = 3.14159
str_num = "{:.2f}".format(float_num)
print(str_num)

Output :

'3.14'

In the example above, the float_num variable holds a float value, and the format() method is used to convert it to a string with two decimal places using the :.2f format specifier. The resulting string ‘3.14’ represents the float value 3.14159 rounded to two decimal places as a string.

3. Using the % operator

The % operator is commonly used for string formatting in Python, similar to how it’s used in C’s printf() function.

For Example:

num = 3.14
str_num = "%s" % num
print(str_num)

Output:

3.14

In this example, %s is a placeholder that indicates a string should be inserted, and % num is used to specify the value that should be inserted into the placeholder.