Python Forum
How do I truncate a variable i Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I truncate a variable i Python
#1
Hi,
I am new to this forum and need some help to my school project.
How can I truncate a variable?
Reply
#2
Hello, if you mean simply discarding the decimal part of a number, you can cast it to an integer:
>>> a = 3.5467
>>> int(a)
3
Reply
#3
(Nov-05-2018, 06:54 PM)j.crater Wrote: Hello, if you mean simply discarding the decimal part of a number, you can cast it to an integer:
 >>> a = 3.5467 >>> int(a) 3 

Thank you for a quick answer. But I can not make it work.
This is my result:

a = 3.5467
print(a)
int(a)
print(a)

--->
Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

3.5467
3.5467

What am I doing wrong.

All the best.
Reply
#4
If you want to change what the variable is referencing, you need to rebind the variable to the new value. int(a) will certainly cast a as an int, but that's a new value. Simply casting it won't change the fundamental meaning of what 3.5467 is. So to rebind the variable, do such: a = int(a)
Reply
#5
Fantastic!
I seems to work.

Thank you!

My first post at this forum and problem solved after some minutes. Thank you.
Reply
#6
Thank you!
It functions.
It works.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020