0

Say I have a variable x. It currently holds the value 4 (x = 4). How would I change the value of x to a floating point number (such as 4.4, or 4.0)? The only thing I can think of is a reassignment, but I feel like this just isn't the right way to do it.

x = x + 0.0

Is there any way to do this with something like a standard library function or without reassignment?

2
  • You don't need to do it, Python will automagically change the data type of a variable based on what you do with it. For example, if x = 4, then you divide it by 3 by doing: x = x / 3 or (x /= 3), you will turn x into a float Commented Apr 10, 2014 at 2:24
  • @Ol'Reliable Unfortunately, division is probably the worst example to choose here, because in python2 your example would have returned 1 because it would assume integer division since both numbers are integers. Perhaps the OP is using python2 and wants to turn the numbers into floats for this exact reason. Commented Apr 10, 2014 at 4:40

1 Answer 1

3

Cast it to float using the pythong in-built function float():

In [154]: x = 4
In [155]: float(x)
Out[155]: 4.0

x = float(x) is all you need.

Sign up to request clarification or add additional context in comments.

1 Comment

You really want x = float(x), but it's the same idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.