Convert Float to String in Python

To convert a float to a string in Python, you can use the string class or a formatted string literal. Both comes built-in with Python. In this tutorial, we’ll guide you step-by-step to achieve this operation.

Use the str() class

Python comes with a str() class returning the string version of an object. If you initial variable is a float, you’ll get the string representation of it.

number = 5.0 number_str = str(number) print(number_str) #'5.0'
Code language: Python (python)

This is the easiest way to convert your float to a string, but it comes with a major disadvantage. If your initial number has numerous decimals (such as 6.78636873298), your string representation will include them all.

As a workaround, you can use a formatted string literal.

Use a formatted string literal

Formatted string literals allows us to include a variable inside a string by appending it with the letter f (which stands for fixed-point notation). Let’s see a simple example:

name = 'John' surname = 'Doe' print(f'My name is {name} and my surname is {surname}') #My name is John and my surname is Doe
Code language: Python (python)

This functionality allows us to create advanced string using variable values. As you can see, we just have to:

  • Include the letter f before the opening quotation mark for our string
  • Wrap our variables inside curly braces

We can use floats and indicate the number of floating points by using a slightly different structure:

number = 5.962389 print(f'{number:.2f}') #'5.96' print(f'{number:.3f}') #'5.962' print(f'{number:.4f}') #'5.9623'
Code language: Python (python)

If you require more digits than the floats actually has, Python will add more 0.

number = 5.1 print(f'{number:.2f}') #'5.10'
Code language: PHP (php)

Use round()

You can also round a number and print it to convert a float to a string with N precisions. Two steps:

  • Use the round() function to round your number
  • Use the str() class object to convert it to a string
number = 5.258977 number_rounded = round(number, 2) #5.26 number_str = str(number_rounded) # '5.26'
Code language: Python (python)

The second arguments of the round() function is used to indicate the number of digits we want after the decimal, which is equivalent to what indicated in the previous section for literals.

  • Round: round(number, 2)
  • Literal: number:.2f

Leave a Reply

Your email address will not be published. Required fields are marked *