>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Answer from Harley Holcombe on Stack Overflow>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Python2 method to check if a string is a float:
def is_float(value):
if value is None:
return False
try:
float(value)
return True
except:
return False
For the Python3 version of is_float see: Checking if a string can be converted to float in Python
A longer and more accurate name for this function could be: is_convertible_to_float(value)
What is, and is not a float in Python may surprise you:
The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") == float(13.4)) is True
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False True So false it becomes true
"123.456" True Decimal
" -127 " True Spaces trimmed
"\t\n12\r\n" True whitespace ignored
"NaN" True Not a number
"NaNanananaBATMAN" False I am Batman
"-iNF" True Negative infinity
"123.E4" True Exponential notation
".1" True mantissa only
"1_2_3.4" False Underscores not allowed
"12 34" False Spaces not allowed on interior
"1,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade True Hexadecimal
"6e7777777777777" True Shrunk to infinity
"1.797693e+308" True This is max value
"infinity" True Same as inf
"infinityandBEYOND" False Extra characters wreck it
"12.34.56" False Only one dot allowed
u'ๅ' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**0 True 0___0 Exponentiation
"-5e-5" True Raise to a negative number
"+1e1" True Plus is OK with exponent
"+1e1^5" False Fancy exponent not interpreted
"+1e1.3" False No decimals in exponent
"-+1" False Make up your mind
"(1)" False Parenthesis is bad
You think you know what numbers are? You are not so good as you think! Not big surprise.
Don't use this code on life-critical software!
Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.
Convert a string to integer with decimal in Python - Stack Overflow
Convert integer to string in Python - Stack Overflow
Python cast a number input value as a string. What's up with that?
How to map/convert a number to string
Videos
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
s = '234.67'
i = int(round(float(s)))
Otherwise, just do:
s = '234.67'
i = int(float(s))
Hello everyone. I'm new to Python and encountered an error while trying to make a simple BMI calculator. I'd like some help on understanding it as well to know if there's a better way of doing it. Thanks and pardon the long winded question in advance.
Here's the code:
print("BMI CALCULATOR\n")
height = input("What is your height(m)?\n")
weight = input("What is your weight(kg)?\n")
bmi = weight / (height * height)
print(height)
print(weight)
print("\nYour bmi is: " + str(bmi))The output:
C:\Users\USER\PycharmProjects\bmiTest\venv\Scripts\python.exe C:\Users\USER\PycharmProjects\bmiTest\main.py
BMI CALCULATOR
What is your height(m)?
1.7
What is your weight(kg)?
72
Traceback (most recent call last):
File "C:\Users\USER\PycharmProjects\bmiTest\main.py", line 7, in <module>
bmi = weight / (height * height)
~~~~~~~^~~~~~~~
TypeError: can't multiply sequence by non-int of type 'str'
Process finished with exit code 1As you can see from this:
Traceback (most recent call last):
File "C:\Users\USER\PycharmProjects\bmiTest\main.py", line 7, in <module>
bmi = weight / (height * height)
~~~~~~~^~~~~~~~
TypeError: can't multiply sequence by non-int of type 'str'The problem seems to be that the inputs were cast as strings, even though they're numbers. As I understand it, Python casts the data type on its own without requiring me to set them. I later avoided this issue by using explicit casting like here:
print("BMI CALCULATOR")print("\n")
height = float(input("What is your height(m)?"))
weight = int(input("What is your weight(kg)?"))
print(height)print(weight) bmi = weight / (height * height)
print("\nYour bmi is: " + str(bmi))The output:
C:\Users\USER\PycharmProjects\bmiCalculator\venv\Scripts\python.exe C:\Users\USER\PycharmProjects\bmiCalculator\main.py BMI CALCULATOR What is your height(m)? 1.7 What is your weight(kg)? 72 1.7 72 Your bmi is: 24.913494809688583 Process finished with exit code 0
But I feel like I'm doing something wrong if I have to do more work to skirt around a feature that's supposed to save time. So again, why does python cast the inputs of weight and height as string, eventhough they're numbers? And is there a better way of doing it?
Hi,
I am trying to write an Icinga check in Python which checks the status of my Keepalived setup. It has several status codes.
I'd like to convert those status codes to something human readable which makes sense. So I am thinking about a dict, something like: state_codes = {0: "init", 1: "backup", 2: "master", 3: "fault", 4: "goto master", 98: "goto fault"} which contains all the possible codes.
I have a JSON object which has the data:
[{
"data": {
"iname": "VRRP_1",
"state": 1,
"wantstate": 1,
}
}]So the thing is I want to print something like VRRP_1 has state <STATE> and wants state <WANTSTATE>, in stead of the numbers.
How would one do that?
Thank you!
Surprisingly, people were giving only solutions that convert to small bases (smaller than the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.
So here is a super simple solution:
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
so if you need to convert some super huge number to the base 577,
numberToBase(67854 ** 15 - 102, 577), will give you a correct solution:
[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455],
Which you can later convert to any base you want
- at some point of time you will notice that sometimes there is no built-in library function to do things that you want, so you need to write your own. If you disagree, post you own solution with a built-in function which can convert a base 10 number to base 577.
- this is due to lack of understanding what a number in some base means.
- I encourage you to think for a little bit why base in your method works only for n <= 36. Once you are done, it will be obvious why my function returns a list and has the signature it has.
If you need compatibility with ancient versions of Python, you can either use gmpy (which does include a fast, completely general int-to-string conversion function, and can be built for such ancient versions โ you may need to try older releases since the recent ones have not been tested for venerable Python and GMP releases, only somewhat recent ones), or, for less speed but more convenience, use Python code โ e.g., for Python 2, most simply:
import string
digs = string.digits + string.ascii_letters
def int2base(x, base):
if x < 0:
sign = -1
elif x == 0:
return digs[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(digs[int(x % base)])
x = int(x / base)
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
For Python 3, int(x / base) leads to incorrect results, and must be changed to x // base:
import string
digs = string.digits + string.ascii_letters
def int2base(x, base):
if x < 0:
sign = -1
elif x == 0:
return digs[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(digs[x % base])
x = x // base
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
Okay, so I had a crash course in Python a looooong time ago, and that's all the prior experience I have with it. I'm starting to dabble in it again, playing around with it to make a text-based game.
In this game, you have stats - Speed, Health, etc etc. Each of these is a number (an int).
I am trying to define a function names statdisplay() so that when I call on it, it prints out your stats. So, if you have a Speed of 1, and the max Speed you can increase that stat to is 5, one of the printed lines would be:
Speed: 1 / 5
This was my ORIGINAL code:
print("\nHealth: " + healthstat + " / " + maxhealth)
print("\nHunger: " + hungerstat + " / " + maxhunger)
print("\nStalking Skill: " + stalkingstat + " / 5")
print("\nHunting Skill: " + huntingstat + " / 5")
print("\nSpeed: " + speedstat + " / 5")
print("\nStrength: " + speedstat + " / 5")But then I got the following error:
TypeError: can only concatenate str (not "int") to str
So I mentally facepalmed myself and looked up how to convert an int to a string, and I keep reading that you can use the str() function (I know there are other ways, but I'm taking baby steps here trying to jog my memory on how everything works before I go doing everything by what's deemed "most appropriate").
This is my NEW code with that in mind:
print("\nHealth: " + str(healthstat) + " / " + maxhealth)
print("\nHunger: " + str(hungerstat) + " / " + maxhunger)
print("\nStalking Skill: " + str(stalkingstat) + " / 5")
print("\nHunting Skill: " + str(huntingstat) + " / 5")
print("\nSpeed: " + str(speedstat) + " / 5")
print("\nStrength: " + str(speedstat) + " / 5")...and yet I am still getting the following error:
TypeError: can only concatenate str (not "int") to str
I can't seem to figure out what's wrong. I do not have the str() function defined as anything else. str() also doesn't seem to come from any special libraries that I'd need to import, but maybe I'm wrong there (I tried to look it up)... the only import I currently have is "import random".
My only other thought is that maybe it's a Google Colab thing, as that's where I'm currently running my code since this wasn't anything serious and I tend to go between two different computers.
Any help would be much appreciated!
Edit: accidentally had the new code in both code boxes.