Convert float to string python

Shahpar Khan

Datatypes

In some languages, the developer needs to explicitly specify the datatype. For example, in C++, variables are declared by first specifying the datatype and then following it with the variable name:

int my_int;
float my_float;
string my_string;

On the other hand, in languages like JavaScript or Python, there is no need to explicitly mention a variable’s datatype at the time of declaration as the datatype is set according to the value assigned to it.

#JavaScript
var my_int = 123
var my_float = 123.123
var my_string = "123"

#Python
my_int = 123
my_float = 123.123
my_string = "123"

Later, after the variable’s initial declaration, it can be type-casted in a different datatype. Type-casting comes in handy when avoiding ambiguous comparisons between different data types and operators/functions performing unexpectedly.

######## FAULTY COMPARISON ########

my_float = 123.123

my_string = "123.123"

equal = (my_float == my_string)

if equal:

print("Variables are equal")

else:

print("Variables are not equal")

######## UNEXPECTED FUNCTIONALITY ########

#Want to concatenate 123.0 and string "my float is: "

#Throws an error

my_float = 123.0

my_string = "my float is: "

result = my_string + my_float

print(result)

Possible errors

To deal with such scenarios, we can easily convert datatypes in Python using type-casting:

SyntaxDescription
str() Cast to string
float() Cast to float
int() Cast to int

To check the type of a variable, use the type() method.

In the code snippet below, observe how we can avoid the error in the previous example by type-casting float to string in Python:

#Want to concatenate 123.0 and string "my float is: "

my_float = 123.0

my_string = "my float is: "

result = my_string + str(my_float)

print(result)

Casting float to string

CONTRIBUTOR

Shahpar Khan

Copyright ©2022 Educative, Inc. All rights reserved

Introduction

In this article, we will use Python’s float() function to convert strings to floats. And we will also use Python’s str() function to convert floats to strings.

It is important to properly convert the data types before using them for calculations and concatenations in order to prevent runtime errors.

Using the float() function

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

Example

Let’s look at an example of converting a string to float in Python:

input_1 = '10.5674'

input_1 = float(input_1)

print(type(input_1))
print('Float Value =', input_1)

Output:


Float Value = 10.5674

The string value of '10.5674' has been converted to a float value of 10.5674.

Why do we need to convert a string to float?

If we are receiving float value from user input through the terminal or reading it from a file, then they are string objects. We have to explicitly convert them to float so that we can perform necessary operations on them, such as addition, multiplication, etc.

input_1 = input('Please enter first floating point value:\n')
input_1 = float(input_1)

input_2 = input('Please enter second floating point value:\n')
input_2 = float(input_2)

print(f'Sum of {input_1} and {input_2} is {input_1+input_2}')

Note: If you are not familiar with string formatting using f prefix, please read f-strings in Python.

Let’s run this code and provide float values for input_1 and input_2:

Please enter first floating point value:
10.234
Please enter second floating point value:
2.456
Sum of 10.234 and 2.456 is 12.69

The resulting sum of 10.234 and 2.456 is 12.69.

Ideally, we should use a try-except block to catch exceptions in case of invalid input from the user.

Using the str() function

We can also convert a float to a string using the str() function. This might be required in situations where we want to concatenate float values.

Example

Let’s look at an example:

input_1 = 10.23
input_2 = 20.34
input_3 = 30.45

# using f-string from Python 3.6+, change to format() for older versions
print(f'Concatenation of {input_1} and {input_2} is {str(input_1) + str(input_2)}')
print(f'CSV from {input_1}, {input_2} and {input_3}:\n{str(input_1)},{str(input_2)},{str(input_3)}')
print(f'CSV from {input_1}, {input_2} and {input_3}:\n{", ".join([str(input_1),str(input_2),str(input_3)])}')

Let’s run this code:

Concatenation of 10.23 and 20.34 is 10.2320.34
CSV from 10.23, 20.34 and 30.45:
10.23,20.34,30.45
CSV from 10.23, 20.34 and 30.45:
10.23, 20.34, 30.45

Concatenating 10.23 and 20.34 produces the string '10.2320.34'. This code also produces two versions of comma-separated values (CSV).

If we don’t convert float to string in the above program, the join() function will throw an exception. Also, we won’t be able to use the + operator to concatenate as it will add the floating point numbers.

Conclusion

You can check out the complete Python script and more Python examples from our GitHub repository.

References:

  • float() official documentation

Can float be converted to string?

The Float. toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.

How do I convert to string in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.

How do you strip a float in Python?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.

Can you convert float to int in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.