I have a number in the form of (how to was parsed from a spreadsheet):
4.10045710008e+12 <type 'float'>
How would I convert this to an integer:
4100457100080
f = 4.10045710008e+12
i = int(f)
Also more simply
a=int(4.10045710008e+12)
if type(value) == float:
value = int(value)
>>> f = 4.10045710008e+12
>>> type(f)
<type 'float'>
>>> int(f)
4100457100080L
>>>
Related
I'm writing a programming language in python, and I need to convert a String into an Integer or a Floating Point Number depending on what the type of the converted value is. I used ternary operators and even created a function that returned the type of a value as a string:
def rtrn_as_str(value):
return str(type(value))[8:-2]
and this is the output:
>>>rtrn_as_str(123)
'int'
>>>rtrn_as_str('A')
'str'
But I couldn't find a way to convert a string into a float or int like in Javascript. Can anyone help me with this?
If you mean convert 'str' to int or float either, You can try this ;
import ast
number = input("Number : ")
print(type(ast.literal_eval(number)))
Output;
Number : 3
<class 'int'>
Number : 3.14
<class 'float'>
I'm not sure if that's what you are trying to do, but casting a string into float can be easily done:
In [32]: some_string = "1.2"
In [33]: some_string_as_float = float(some_string)
...:
In [34]: print(some_string_as_float)
1.2
In [35]: type(some_string_as_float)
Out[35]: float
If you want to try cast it into integer first:
In [36]: some_other_string = "1"
In [37]: def cast(string):
...: try:
...: return int(string)
...: except:
...: return float(string)
...:
In [38]: cast(some_string)
Out[38]: 1.2
In [39]: cast(some_other_string)
Out[39]: 1
I'm trying to test for equality of a and b here. I'm not sure why the output prints 'not equal' even though both a and b equates to '75', which is the same value.
a = (len(products)) #products is a dictionary, its length is 75
b = (f.read()) #f is a txt file that contains only '75'
if(str(a) == str(b)):
print ('equal')
else:
print ('not equal')
Add an int() around the f.read() to typecast the str to an int.
>>> b = f.read().strip() # call strip to remove unwanted whitespace chars
>>> type(b)
<type 'str'>
>>>
>>> type(int(b))
<type 'int'>
>>>
>>> b = int(b)
Now you can compare a and b with the knowledge that they'd have values of the same type.
File contents are always returned in strings/bytes, and you need to convert/typecase accordingly.
The value of 'a' is 75 the integer while the value of 'b' is "75" the string. When calculated if equal the result will be false because they are not the same type. Try casting b to an integer with:
b = int(b)
I would like to convert a hex string to be an int but without the value changing.
For example
>>> int_value = 0xb19bc74cf4
>>> print type(int_value)
<type 'int'>
Now i have a string
>>> str_value = "0xb19bc74cf4"
>>> print type(str_value)
<type 'str'>
How do i now convert str_value to be an int_value?
Desired value outcome would be:
input: str_value = "0xb19bc74cf4"
Output: int_value = 0xb19bc74cf4
Print of int_value to be 0xb19bc74cf4
print of type(int_value) to be <type 'int'>
You need to realize that an int is internally a binary value. There is no way to "remain as a hex value but as type int". print converts it back to a string for display, and you can use format to customize the conversion:
>>> str_value = '0xb19bc74cf4'
>>> str_value
'0xb19bc74cf4'
>>> n = int(str_value,16)
>>> print(n) # default is to print in base 10
762822741236
>>> print(format(n,'#x')) # format in base 16 with "0x" prepended.
0xb19bc74cf4
If i have
a = "3.14, ABCF , 2.16"
and type(a) returns "str"
how may i convert this into a list or tuple and keep the type integrity of elements inside.(ex: running through the collection and check type should return float, string, float, respectively)
I did this using regular expression
import re
a = "3.14, ABCF , 2.16 , 9"
b=a.split(",") #break string
for c in b:
x=c.strip() # removes whitespace character
if x.isdigit(): #return bool value
print("int")
elif bool(re.search('[a-zA-Z]+', x)):
print("string")
elif bool(re.search('[0-9.]+', x)):
print("float")
OUTPUT :
float
string
float
int
OR
By using python ast library
from ast import literal_eval
def get_type(data):
try:
return type(literal_eval(data))
except (ValueError, SyntaxError):
# A string, so return str
return str
a = "3.14, ABCF , 2.16 , 9, True"
b=a.split(",")
for c in b:
x=c.strip()
print(get_type(x))
OUTPUT:
<class 'float'>
<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>
I recently ran into this in Python 3.5:
>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
int(flt)
ValueError: invalid literal for int() with base 10: '3.14'
Why is this? It seems like it should return 3. Am I doing something wrong, or does this happen for a good reason?
int() expects an number or string that contains an integer literal. Per the Python 3.5.2 documentation:
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. (Emphasis added)
Meaning int() can only convert strings that contain integers. You can easily do this:
>>> flt = '3.14'
>>> int(float(flt))
3
This will convert flt into a float, which is then valid for int() because it is a number. Then it will convert to integer by removing fractional parts.
It does not work because flt is not a string representation of an integer. You would need to convert it to float first then an int.
e.g.
flt = '3.14'
f = int(float(flt))
output is
3
The other answers already give you a good explanation about your issue, another way to understand what's going would be doing something like this:
import sys
for c in ['3.14', '5']:
try:
sys.stdout.write(
"Casting {0} {1} to float({0})...".format(c, c.__class__))
value = float(c)
sys.stdout.write("OK -> {0}\n".format(value))
print('-' * 80)
except:
sys.stdout.write("FAIL\n")
try:
sys.stdout.write(
"Casting {0} {1} to int({0})...".format(c, c.__class__))
value = int(c)
sys.stdout.write("OK -> {0}\n".format(value))
except:
sys.stdout.write("FAIL\n")
sys.stdout.write("Casting again using int(float({0}))...".format(value))
value = int(float(c))
sys.stdout.write("OK -> {0}\n".format(value))
print('-' * 80)
Which outputs:
Casting 3.14 <class 'str'> to float(3.14)...OK -> 3.14
--------------------------------------------------------------------------------
Casting 3.14 <class 'str'> to int(3.14)...FAIL
Casting again using int(float(3.14))...OK -> 3
--------------------------------------------------------------------------------
Casting 5 <class 'str'> to float(5)...OK -> 5.0
--------------------------------------------------------------------------------
Casting 5 <class 'str'> to int(5)...OK -> 5