Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | No |
Requirements | Python |
Time | 1m |
You may also need to use float(s) to convert a string or number to a floating point number or combination of both as follows:
int(s)
float(s)
int(float(s))
Examples
x = '123456'
Confirm the object type:
type(x)
Sample outputs:
<type 'str'>
Convert a string to an int and store it to i, run:
i = int(x) type(i)
Sample outputs:
<type 'int'>
However, the following string to int will fail:
x='123456.334' y=int(x)
Sample outputs:
ValueError Traceback (most recent call last) /home/vivek/ in () ValueError: invalid literal for int() with base 10: '123456.334'
Try the following solution:
x='123456.334' y=int(float(x)) type(x) type(y) print y a='12.5' b='13.5' print( int(float(a))+ int(float(b)) )
Finally, you can also use floating point class for decimal arithmetic:
x='123.34' import decimal i=int(Decimal(x)) print(i) type(i)
🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.
🐧 10 comments so far... add one ↓
🐧 10 comments so far... add one ↓
Category | List of Unix and Linux commands |
---|---|
File Management | cat |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Network Utilities | dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • jobs • killall • kill • pidof • pstree • pwdx • time |
Searching | grep • whereis • which |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Hey, I get an error output when I input i=int(Decimal(x)), NameError: name ‘Decimal’ is not defined. Forgive me, I’m new to Python. Can you explain this?
I DONT REALLY KNOW BUT I CAN FIND OUT FOR YOU AND ANYWAY THTS THE EXACT SAME THING IM STUCK ON
Hi, try to write your Decimal like this (decimal):
x=’123.34′
import decimal
i=int(decimal.Decimal(x))
print(i)
type(i)
Bonjour
J’ai un problème avec mon programme , puis-je vous le montrer afin que vous m’aidiez ?
dans mon programme j’aimerai convertir un format str en int afin de faire une série de calcule
Hi!
im a python-beginner and dont know much about programming yet..
so i ve got the “programming in python3” book
my question:
page55
i ve got problems to understand int(s , base)
it would be nice to get a simple example!
thnx:)!
Im getting the error:
Please help me
thanks
Good. But how do you convert the string ‘5.3.5’ to float number?
how can i turn a sentence that a user has input into numbers