How to print specific number right of the decimal point - python

1.45
4
Hey everyone i need to print number right of the decimal point like if i input 1.45 it needs to output 4 because its first number after point i also tried multiplying by 10 or 100 but i dont know much numbers will be after point so if there is 3 numbers after point youn still need to print the first number after point. I have tried using ".2f" which didnt work it just made things worse i also tried finding things in internet all i found was about ".2f".

You could just multiply by 10, ignore any fractional component by converting to int then print the value modulus 10. Like this:
n = 1.45
print(int(n * 10) % 10)
Output:
4

Use format with a floating-point format specifier to convert a number to a string:
x = 1.45
'{:f}'.format(x) # '1.45'
(the format specifier is needed to avoid using scientific notation like
1e-09)
Use split to find the fractional part:
x = 99
'{:f}'.format(x).split('.') # ['99', '000000']
Take the second part from the list:
x = -3.1415
'{:f}'.format(x).split('.')[1] # '141500'
Then take the first character:
x = 1.45
print('{:f}'.format(x).split('.')[1][0]) # 4
With a slight modification, this will work to extract any decimal digit:
x = 0.000000000001234
print('{:20f}'.format(x).split('.')[1][12]) # 12th decimal is 2
Here, I used 20 to generate enough decimals (default is 6).

Related

Python not returning all the zeros but e-n

I have a python code that when given a small number between 0 and 1 doesn't print it fully, but 4.43017984825e-7 for example,how do I make the code shows the whole number with all zeroes?
this was my try:
number="4.43017984825e-7"
result=number.find("e")
new=list(number)
last=int(new[-1])
print(last)
del new[13:16]
print(new)
pricee=(''.join(new))
print(pricee)
price=float(pricee)*10**-(last)
print(price)
Note: the number changes everytime, so I want it to be applicable for all numbers.
You can probably accomplish what you want with fixed-point formatting.
>>> x=4.43017984825e-7
>>> print(x)
4.43017984825e-07
>>> print(f"{x:20.18f}")
0.000000443017984825
The 20 in that format tells the full width you want, while the 18 tells the number of decimals.
Now, this is fairly specific to this number, you'll have to pick the right length and number of decimals for your actual application.
Expanding on the suggestion from #MostafaFarzán: you can use log10 to adjust that fixed point formatting to any number:
x = <some float>
significant_digits = 8
decimals=max(0, int(-log10(x) + significant_digits))
print(f"%.{decimals}f" % x)
or, more concisely but harder to read:
print(f"%.{max(0, int(-log10(x) + 8))}f" % x)

How to check if a float value is within a certain range and has a given number of decimal digits?

How to check if a float value is within a range (0.50,150.00) and has 2 decimal digits?
For example, 15.22366 should be false (too many decimal digits). But 15.22 should be true.
I tried something like:
data= input()
if data in range(0.50,150.00):
return True
Is that you are looking for?
def check(value):
if 0.50 <= value <= 150 and round(value,2)==value:
return True
return False
Given your comment:
i input 15.22366 it is going to return true; that is why i specified the range; it should accept 15.22
Simply said, floating point values are imprecise. Many values don't have a precise representation. Say for example 1.40. It might be displayed "as it":
>>> f = 1.40
>>> print f
1.4
But this is an illusion. Python has rounded that value in order to nicely display it. The real value as referenced by the variable f is quite different:
>>> from decimal import Decimal
>>> Decimal(f)
Decimal('1.399999999999999911182158029987476766109466552734375')
According to your rule of having only 2 decimals, should f reference a valid value or not?
The easiest way to fix that issue is probably to use round(...,2) as I suggested in the code above. But this in only an heuristic -- only able to reject "largely wrong" values. See my point here:
>>> for v in [ 1.40,
... 1.405,
... 1.399999999999999911182158029987476766109466552734375,
... 1.39999999999999991118,
... 1.3999999999999991118]:
... print check(v), v
...
True 1.4
False 1.405
True 1.4
True 1.4
False 1.4
Notice how the last few results might seems surprising at first. I hope my above explanations put some light on this.
As a final advice, for your needs as I guess them from your question, you should definitively consider using "decimal arithmetic". Python provides the decimal module for that purpose.
float is the wrong data type to use for your case, Use Decimal instead.
Check python docs for issues and limitations. To quote from there (I've generalised the text in Italics)
Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.
no matter how many base 2 digits you’re willing to use, some decimal value (like 0.1) cannot be represented exactly as a base 2 fraction.
Stop at any finite number of bits, and you get an approximation
On a typical machine running Python, there are 53 bits of precision available for a Python float, so the value stored internally when you enter a decimal number is the binary fraction which is close to, but not exactly equal to it.
The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero.
And finally, it recommends
If you’re in a situation where you care which way your decimal halfway-cases are rounded, you should consider using the decimal module.
And this will hold for your case as well, as you are looking for a precision of 2 digits after decimal points, which float just can't guarantee.
EDIT Note: The answer below corresponds to original question related to random float generation
Seeing that you need 2 digits of sure shot precision, I would suggest generating integer random numbers in range [50, 15000] and dividing them by 100 to convert them to float yourself.
import random
random.randint(50, 15000)/100.0
Why don't you just use round?
round(random.uniform(0.5, 150.0), 2)
Probably what you want to do is not to change the value itself. As said by Cyber in the comment, even if your round a floating point number, it will always store the same precision. If you need to change the way it is printed:
n = random.uniform(0.5, 150)
print '%.2f' % n # 58.03
The easiest way is to first convert the decimal to string and split with '.' and check if the length of the character. If it is >2 then pass on. i.e. Convert use input number to check if it is in a given range.
a=15.22366
if len(str(a).split('.')[1])>2:
if 0.50 <= value <= 150:
<do your stuff>>

Python multiply range

i need to get a list of numbers derived from a range(15,20,1), were each number is 15*x*100:
X Y
15 100
16 93,75
17 88,2352941176
18 83,3333333333
19 78,9473684211
20 75
The result should be an array of y with two decimals.
I tried with python and it took me a while to find out that it will only handle integers. Then I tried numpy, but I am still not getting there. I am a nub, so sorry for the stupidity of the question, but after trying for two hours I decided to post a question.
Best,
Mace
Do you need something like:
ylist = [float(x)*15*100 for x in range(15,21)]
?
This would return:
[22500.0, 24000.0, 25500.0, 27000.0, 28500.0, 30000.0]
I'm not quite sure what your Y column means, since your formula 15*x*100 doesn't generate those values.
If you actually mean x*100/15, it would be:
ylist = [15/float(x)*100 for x in range(15,21)]
Or even simpler:
ylist = [15.0/x*100.0 for x in range(15,21)]
If all the values in a calculation are of type int, python will create an int as result. If, on the other hand, one of them is a float or double, that'll be the type of the result.
This coercion can be done both explicitly using float(x), or simply having one of your constants represented as a floating point value, like 100.0.
As to the 2 decimal places need, it depends on what you need to do with the values.
One way is to use round to 2 decimal places, like:
ylist = [round(15.0/x*100.0, 2) for x in range(15,21)]
If you always need two decimal places, probably you'll want to use string formatting, check #mgilson reply for that.
Perhaps you're looking for something like:
>>> print [float(15)/x*100 for x in range(15,21)]
[100.0, 93.75, 88.23529411764706, 83.33333333333334, 78.94736842105263, 75.0]
This doesn't give you the number to 2 decimal places. For that you'll need round or string formatting ... (I'm not sure exactly what you want to do with the numbers after the fact, so it's hard to give a recommendation here). Here's an example with string formatting:
>>> print ['{0:.2f}'.format(float(15)/x*100) for x in range(15,21)]
['100.00', '93.75', '88.24', '83.33', '78.95', '75.00']

How to identify the tenths part of a float in Python?

After looking at the various math, float, and decimal functions in Python, I haven't found what I'm looking for. In my program, there may be instances when it will return a float and I need the float information so that I can do another function. Let's say based on the user's input the quotient we're working with is 1.4, which I will represent as X.Y. How do I isolate Y so that I can use a FOR statement. (I need the program to do something 4 times in this case.) I've tried playing with the % function, but that returns the remainder, not the value I'm looking for. I've tried math.fmod and math.modf. Again not what I'm looking for. I looked at this example too.
Looks like int((x*10) % 10) will do it:
>>> x = 1.4
>>> int((x*10) % 10)
4
How about
x = 1.4
y = 10 * (x - int(x))
>>> 4
or you could do it as string manipulation
x=1.4
whole,fractional = map(int,str(x).split("."))
afterwards whole is equal to 1 and fractional is equal to 4... and it should work equally well with negative numbers
Using the following method you can get any position in a float. That is, tenths, hundredths, thousandths and so on:
import math
def get_pos_float(num, unit):
if unit >= 10:
num = abs(math.modf(num)[0]) # Get just the fractional part
num *= 10 # Move the decimal point one place to the right
return get_pos_float(num, unit/10)
return int(math.modf(num)[1]) #Return the whole number part
decimalNumber = 13.24
print(get_pos_float(decimalNumber, 10)) # prints the tenths decimal position 2
print(get_pos_float(decimalNumber, 100)) # prints the hundredths decimal position 4
print(get_pos_float(decimalNumber, 1000)) # prints the thousandths decimal position 0

Format a number containing a decimal point with leading zeroes

I want to format a number with a decimal point in it with leading zeros.
This
>>> '3.3'.zfill(5)
003.3
considers all the digits and even the decimal point. Is there a function in python that considers only the whole part?
I only need to format simple numbers with no more than five decimal places. Also, using %5f seems to consider trailing instead of leading zeros.
Is that what you look for?
>>> "%07.1f" % 2.11
'00002.1'
So according to your comment, I can come up with this one (although not as elegant anymore):
>>> fmt = lambda x : "%04d" % x + str(x%1)[1:]
>>> fmt(3.1)
0003.1
>>> fmt(3.158)
0003.158
I like the new style of formatting.
loop = 2
pause = 2
print 'Begin Loop {0}, {1:06.2f} Seconds Pause'.format(loop, pause)
>>>Begin Loop 2, 0002.1 Seconds Pause
In {1:06.2f}:
1 is the place holder for variable pause
0 indicates to pad with leading zeros
6 total number of characters including the decimal point
2 the precision
f converts integers to floats
print('{0:07.3f}'.format(12.34))
This will have total 7 characters including 3 decimal points, ie. "012.340"
Like this?
>>> '%#05.1f' % 3.3
'003.3'
Starting with a string as your example does, you could write a small function such as this to do what you want:
def zpad(val, n):
bits = val.split('.')
return "%s.%s" % (bits[0].zfill(n), bits[1])
>>> zpad('3.3', 5)
'00003.3'
With Python 3.6+ you can use the fstring method:
f'{3.3:.0f}'[-5:]
>>> '3'
f'{30000.3:.0f}'[-5:]
>>> '30000'
This method will eliminate the fractional component (consider only the whole part) and return up to 5 digits. Two caveats: First, if the whole part is larger than 5 digits, the most significant digits beyond 5 will be removed.
Second, if the fractional component is greater than 0.5, the function will round up.
f'{300000.51:.0f}'[-5:]
>>>'00001'

Categories

Resources