So far, I would do int(float('3.5'))
Any other good way to do?
Note: 3.5 is a string.
I want to use the the built-in API that specify for this sort of problem.
You're on the right track, and the best solution is probably as mentioned:
>>> int(float("3.5"))
This truncates the float.
If you want a different type of rounding, you can use the math package:
>>> import math
>>> x = "3.5"
>>> math.floor(float(x)) # returns FP; still needs to be wrapped in int()
3.0
>>> math.ceil(float(x)) # same
4.0
>>> math.trunc(float(x)) # returns an int; essentially the same as int(float(x))
3
If on the other hand you wish to round the number to the nearest integer, you may use the floating-point built-in operation round before converting to an integer, e.g.
>>> int(round(float(x))) # 3.5 => 4
4
>>> int(round(3.4999))
3
The only code which could possibly be simpler and clearer than what you have is int('3.5'), which doesn't work. Therefore, what you have is the simplest, clearest working code.
All that you need is
int(3.5)
Note that this truncates; it doesn't round.
Maybe int(eval('3.5'))
Related
I have a variable that is a float, and I can't find out how to round it down.
I did a google search and it said I should use trunc, but trunc didn't work for me.
if you always want to round down and are getting positive floats, just use int() .. otherwise you can use math.floor(), which can handle negative floats too
>>> math.floor(3.99)
3
>>> int(-0.1)
0
>>> int(-1.2)
-1
>>> math.floor(-1.2)
-2
I'm looking for a way to neatly show rounded floats of varying decimal lengh.
Example of what I'm looking for:
In: 0.0000000071234%
Out: 0.0000000071%
In: 0.00061231999999%
Out: 0.0061%
In: 0.149999999%
Out: 0.15%
One way to do it would be:
def dynamic_round(num):
zeros = 2
original = num
while num< 0.1:
num*= 10
zeros += 1
return round(original, zeros)
I'm sure however there is a much cleaner way to do the same thing.
Here's a way to do it without a loop:
a = 0.003123
log10 = -int(math.log10(a))
res = round(a, log10+2)
==> 0.0031
This post answers your question with a similar logic
How can I format a decimal to always show 2 decimal places?
but just to clarify
One way would be to use round() function also mentioned in the documentation
built-in functions: round()
>>> round(number[,digits])
here digit refers to the precision after decimal point and is optional as well.
Alternatively, you can also use new format specifications
>>> from math import pi # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'
here the number next to f tells the precision and f refers to float.
Another way to go here is to import numpy
>>>import numpy
>>>a=0.0000327123
>>>res=-int(numpy.log10(a))
>>>round(a,res+2)
>>>0.000033
numpy.log() also, takes an array as an argument, so if you have multiple values you can iterate through the array.
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
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))
>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
You don't specify if you want rounding or not...
You could use:
s = '23.245678'
i = int(float(s))
"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.
You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).
round(float('23.45678'))
The expression int(float(s)) mentioned by others is the best if you want to truncate the value. If you want rounding, using int(round(float(s)) if the round algorithm matches what you want (see the round documentation), otherwise you should use Decimal and one if its rounding algorithms.
round(float("123.789"))
will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:
int(float("123.789"))
But, again, actual 'type' is usually not that important.
I believe this is a useless bug that should be corrected in Python.
int('2') --> 2 That converts the string '2' into an the integer 2.
int(2.7) --> 2 Converts a float to an int.
int('2.7') SHOULD convert to 2. This is how Perl works, for example. Yes, this does two things at once. It converts the string and when it finds it is in a representation that is a float, it should convert to int.
Otherwise, why insist that float('2') should work? It is an integer string, because there is no decimal point. So it has to convert from string which is an integer, directly to float.
I don't know but perhaps someone can answer whether the python interpreter, if the required int(float(x)) is used, if it actually goes through the process of first converting to float and then converting to int. That would make this bug even more critical to correct.
I think if I'd know the math behind it I might have figured it out by myself.
When I call math.log10(0.0000000000001) I get -13. But how do I convert this back into 0.0000000000001? and how i'd handle it when using math.log(0.0000000000001)?
Both ways, the fundamental, arithmetic one and the one using a built-in python function would interest me.
a = math.log10(0.0000000000001)
b = 10 ** a
math.log() takes two parameter, a number and a base. Default value is e (mathematical constant), a special constant which tends to 2.71828.
You can get the number by evaluating base to the power log_value
>>> a = math.log(10)
>>> a
2.302585092994046
>>> 2.71828**a
9.999984511610785
If I would take e's value with higher precision, I can get the result close to 10.
Or, you can use math.exp()
>>>math.exp(a)
10.000000000000002
You can also use math.pow()
>>> math.pow(2.71828,a)
9.999984511610785
Looking to format a output to show a very small number..
a= 6500
b= 3600
c=.000900
d= int((b/a)-c)
print d
Answer comes out to be zero, but looking for the .###### numbers after the .
sorry try this
Looks like you got bitten by integer division in python 2.x.
>>> a= 6500
>>> b= 3600
>>> c=.000900
>>> from __future__ import division
>>> print b/a - c
0.552946153846
There may be two issues with your calculation:
If you're using Python 2, division using / between two integers will always be an integer also. This will discard the fractional part of the calculation, which can be unexpected. One fix for this is to force one of the values to be a float value (e.g. float(b)/a). An alternative is to put at the top of your file from __future__ import division, which tells Python to use the Python 3 semantics for division (you'll only get an integer from integer division if the result is an exact integer).
The second issue seems to be about formatting a floating point value. First you seem to want only the fractional part of the value (not the integer part). Usually the best option is to simply subtract the integer part of the value:
d = someFloatingPointValue()
d_frac = d - int(d)
Next, to get a string to output (where you want several decimal places, but not a huge number of them), you probably want to explore Python's string formatting operations:
d = someFloatingPointValue()
d_to4decimalPlaces = "{:.4f}".format(d)