You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.
With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).
Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.
For example,
>>> 125650429603636838/(2**53)
13.949999999999999
>>> 234042163/(2**24)
13.949999988079071
>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999
If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:
- Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
- Or use a fixed point number like decimal.
You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.
With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).
Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.
For example,
>>> 125650429603636838/(2**53)
13.949999999999999
>>> 234042163/(2**24)
13.949999988079071
>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999
If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:
- Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
- Or use a fixed point number like decimal.
There are new format specifications, String Format Specification Mini-Language:
You can do the same as:
"{:.2f}".format(13.949999999999999)
Note 1: the above returns a string. In order to get as float, simply wrap with float(...):
float("{:.2f}".format(13.949999999999999))
Note 2: wrapping with float() doesn't change anything:
>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
Is there a way to limit the number of digits in an integer with Python?
python - How to limit the number of digits? - Stack Overflow
python - How can I limit the amount of digits in an input? - Stack Overflow
python - How do I limit an output's maximum number of characters? - Stack Overflow
Videos
So sometimes math will make some absurdly long number that almost no one needs like
Which is unnecessary for most applications, but the float values are needed and can't be substituted for integers
So how can I turn 3.182736282647273 into 3.18? Or something like that
Original result value: 15.5884572681
Use floor to round down to get 15.58:
import math
def solution(side):
result = (side**2)*(3**(0.5))/4
return math.floor(result*100)/100
print(solution(6)) # prints 15.58
Use round with precision 2 to get 15.59:
def solution(side):
result = (side**2)*(3**(0.5))/4
return round(result,2)
print(solution(6)) # prints 15.59
def solution(side):
result = (side**2)*(3**(0.5))/4
return round(result,2)
# return = 15.59
You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b
print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
if len(a) > 1:
print ("Error. Only 1 digit allowed!")
a = int(a)
aa = (a*10)
b = raw_input("SECOND NUMBER: ")
if len(b) > 1:
print ("Error. Only 1 digit allowed!")
b = int(b)
bb = (b*10)
Or more simply:
You could ask for the number and keep asking until the length is 10 and the input is a number
num = raw_input('Please enter your 10 digit number:')
while len(num) != 10 or (not num.isdigit()):
print 'Not a 10 digit number'
num = raw_input('Please enter your 10 digit number:')
num = int(num)
print 'The final number is: ', num
I suggest creating a function to handle of of the prompting, then call it in your code. Here is a simplfied example:
def single_num(prompt):
num = ""
while True:
num = raw_input(prompt)
if len(num) == 1:
try:
return int(num)
except ValueError:
print "Error, you must enter a number"
else:
print "Try again, now with a single number"
This will take a prompt, and ask it over and over again until it recieves a 1 length string. To make this more user friendly, you can add in protections with try...except for non-numerical input and whatnot
The problem you're having is confusion between a number, and a string representation of a number. These are different things.
When you do this:
nCost = '%.2f'%(nCost*1.25)
… you're multiplying your number by 1.25, then replacing it with a string that represents the number up to two decimal points. So, when you do this:
nCost = nCost * 1.25
… you're trying to multiply a string by 1.25, which makes no sense.
I suspect you didn't want a string here at all; you just wanted to round the number as a number. To do that, use the round function:
nCost = round(nCost*1.25, 2)
Of course as soon as you multiply by 1.25 again, you may "unround" it by another decimal place or two:
>>> nCost = 1.33333
>>> nCost = round(nCost*1.25, 2)
>>> nCost
1.33
>>> nCost = nCost * 1.25
>>> nCost
1.6625
And really, it's almost always a bad idea to round values before doing arithmetic on them; that just multiplies rounding errors unnecessarily. It's better to just keep the highest-precision value around as long as possible, and round at the last possible second—ideally by using %.2f/{:.2f} formatting in the printing/writing-to-disk/etc. stage.
Another thing to keep in mind is that not all real numbers can be represented exactly as floats. So, for example, round(13.4999, 2) is actually 13.949999999999999289457264. A simple repr or str or %f will print this out as 13.95, so you may not notice… but it's still not exactly 13.95.
The best way to solve this problem, and your other problems, is to use the Decimal type instead of the float type. Then you can round the value to exactly 2 decimal places, do math in a 2-decimal-places context, etc.
One way to do this would be with the following:
def costEdit(nCost):
nCost = '%.2f'%(nCost*1.25)
#nCost = nCost*1.25
return nCost
Let me break this down for you.
Take the line:
'%.2f'%(nCost*1.25)
And break it down into its components:
(' ( (%) .2f) ')%(nCost*1.25)
- Everything inside
''is just a normal string. - The
%is a symbol that means "substitute in later". .2fis a command in Python that truncates 2 places after a decimal.%(nCost*1.25)means "nCost*1.25is what you put in place of%"
So in order, it does the math of nCost*1.25, puts it inside the string, then cuts off everything else and gives you what is left.
Take note that I've rewritten your costEdit function to accept nCost as an argument. This means that now you can call:
costEdit(nCost)
with any number that you want, and it will do the math.
Also note I've replaced print with return. This means that now, you will have to write:
print costEdit(80)
to get
100
However it now means you can do math with costEdit, such as:
print 4*costEdit(80)
and instead of printing 100 along the way, it will just print
400
Questions? Leave a comment.
Happy coding!
EDIT: Regarding your error,
I think I've reproduced it and understand the problem.
When I type:
costEdit('15')
I get your error.
This is because when you do costEdit('15'), you're entering '15' and not 15. If a value is between '' or "", you're dealing with a value of type string.
In python, you can't multiply a float (type of number) with a string. That's what this is complaining about.
To remedy the situation, just remove the quotes. Then you're entering a number of type float or int (integer), both of which can be multiplied by a float (the value 1.25 inside costEdit()).
I hope this solves your issue-- I have to get off the PC for the night. If it doesn't help, leave a comment and I'll return tomorrow.
Otherwise, I'm glad I could help and remember to select a best answer on your question, so those who helped can get their precious precious pointssssss
The formating method for both integer and decimal is
>>> '{:06.2f}'.format(3.141592653589793)
'003.14'
the part before the . (6 here) denotes the total length of padding (including the .), and after the . (2fhere) denotes digits after decimal point.
Hope it helps. checkout the link.
You can try to do something like this
print('{:.6}'.format(val))
I am working on something and I need to handle numbers of over 2000-3000 digits and print them. Which data type in Python should I use. Java has a data type BigDecimal which can be used, is there any similar data type in Python
Let:
>>> num = 0.0012345
For up to 3 significant figures:
>>> f'{num:.3}'
'0.00123'
For 3 decimal places:
>>> f'{num:.3f}'
'0.001'
See the "presentation types for floating point and decimal" table at the bottom of this section for any additional requirements provided by e, E, f, F, g, G, n, %, None.
You could use the string formatting operator %:
In [3]: val = 1./3
In [4]: print('%.15f' % val)
0.333333333333333
or str.format():
In [8]: print(str.format('{0:.15f}', val))
Out[8]: '0.333333333333333'
In new code, the latter is the preferred style, although the former is still widely used.
For more info, see the documentation.
If i got this right this should work:
a=input()
if len(a)==9 and a[0] != '0' and a.isdigit():
#if you want it to be integer
a=int(a)
do something
Hope it helps.
Well if I understood correctly you need a program that asks the user to enter exactly 9 digits. In that case it's pretty simple.
i = input("Enter a nine digit number: ")
if len(i) != 9:
print("You must enter 9 digits!")
quit()
if not i.isdigit():
print("Your input must be a number!")
quit()
# num is a 9 digit integer
# i is a 9 digit string
num = int(i)