float number with leading zero at end on python - python

I want to convert string number to float and keep zeros at the end like this f=float('.270') and f should be 0.270, not 0.27 or '0.270' how I can do it?

Depending of the application, you should use the Decimal lib - specially if you are dealing with critical calculations like money
https://docs.python.org/3.8/library/decimal.html
import decimal
decimal.getcontext().prec = 3
f = decimal.Decimal('0.270')
print(f)
Or simply "%.3f" % f

Have you considered saving the float as a string rather than a float? If needed for calculations then it can be casted to a float. If you need to have this for significant figures, then this article on rounding numbers in Python should help. It uses the format() method.
I hope this was able to help!
phylo

Related

Dealing with decimals with many digits in Pandas,

pd.set_option('display.max_colwidth', None )
pd.set_option('display.float_format', lambda x: '%.200f' % x)
exData = pd.read_csv('AP11.csv',delimiter=';',float_precision=None)
x = exData.loc[:,['A','B']]
y = exData.loc[:,['C']]
x
my original float on excel is 0.1211101931541032183754113717355410323332315436353654273243543132542237415430173719
what is being displayed is
0.12111019315410319341363987177828676067292690277099609375000000000000000000000000000000000000000000000000000000000...
this is not a display issue. something in pandas rounds my float. i don't want to round any number for it will affect the result of my string. because this is originally a string that is converted to a float. i tried to use int64 but it can't handle big numbers. so instead i decided to use floats with "0.mystring" to not get "inf" displayed in pandas. and i get it rounded. is machine learning limited by these missy variables? or is there another way to deal with big numbers without rounding, displaying inf?
Use decimal instead of float. Just put
from decimal import Decimal
at the top of your code, and write your floats as
x = Decimal(0.121110193154103218375411371735541032333231543635365427324354313254223741543017371)
decimal is a library for floats with a dynamic length, rather than rounded.
Generally you should avoid floats, as they can have strange irregularities and roundings. Often when operations are performed on them, they can have a series of zeros and then some other numbers, when it should just have a few decimal places.

How to display the decimal points in python

I am trying to write a python script that divides two numbers and then stores the value of the first digit after the decimal point but first I want to print the answer of the division.
example:
31/7 should be 4,428 but when I use
def spiel():
anzahl=int(raw_input("Anzahl der Spieler"))
spieler=int(raw_input("Jeder wievielte spielt"))
if anzahl>0 and spieler>0:
#Quotient berechnen
q=anzahl/spieler
print '%.2f'%q
I get the answer 4.00, what have I done wrong.
If you could tell me how I can store the first decimal point after the decimal point THAT WOULD BE AMAZING!
Thanks in advance
In python2.7:
If you divide two integer, answer will be integer always as it will skip the decimal value.
If you want precise float output, try this:
>>>float(10)/3
>>>3.3333333333333335
Any of the value should be float.
You're dividing an int by an int. You should use floats
def spiel():
anzahl=float(raw_input("Anzahl der Spieler"))
spieler=float(raw_input("Jeder wievielte spielt"))
if anzahl>0 and spieler>0:
#Quotient berechnen
q=anzahl/spieler
print '%.2f'%q
In response to comment:
There are multiple ways to do that, what's best would depend on your applicaiton:
q =anzahl/spieler
print "{}".format(int(10*(q%1)))
print "{}".format(int((q-int(q))*10))
print "{}".format(str(a).split(".")[1][0])
and probably some easier ones that I didn't think of
The thing that you are doing wrong here is, you are making it believe that operands of division are integers( during division) .
I am sure you want to take two integers. You can do following things:
use float() during division. In here you do not need to convert both Anzahl and spieler to float. Just convert spieler :
q = anzahl/float(spieler)
**2. Use future module. then you do not need to change anything in your code. Write the following line at the beginning of your code :
from __future__ import division
Use Python 3. In python 3 '/' means you will non-truncating division and '//' means truncating division
If you divide an integer by an integer you will receive an integer. An integer is a whole number, no decimal points.
If you divide a float/integer by a float you will receive a float. A float is a whole number, including decimal points.
When you are doing your operations, change spieler to a float. That can be done with float(spieler).
Your code will look like this:
def spiel():
anzahl=int(raw_input("Anzahl der Spieler"))
float(spieler)=int(raw_input("Jeder wievielte spielt"))
if anzahl>0 and spieler>0:
#Quotient berechnen
q=anzahl/spieler
print '%.2f'%q

How to print floating point numbers as it is without any truncation in python?

I have some number 0.0000002345E^-60. I want to print the floating point value as it is.
What is the way to do it?
print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.
Like this?
>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754
As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.
Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.
You could also use decimal to not lose the precision due to binary float truncation:
>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
You can use decimal.Decimal:
>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'
This is the actual value of float created by literal 0.0000002345e-60. Its value is a number representable as python float which is closest to actual 0.0000002345 * 10**-60.
float should be generally used for approximate calculations. If you want accurate results you should use something else, like mentioned Decimal.
If I understand, you want to print a float?
The problem is, you cannot print a float.
You can only print a string representation of a float. So, in short, you cannot print a float, that is your answer.
If you accept that you need to print a string representation of a float, and your question is how specify your preferred format for the string representations of your floats, then judging by the comments you have been very unclear in your question.
If you would like to print the string representations of your floats in exponent notation, then the format specification language allows this:
{:g} or {:G}, depending whether or not you want the E in the output to be capitalized). This gets around the default precision for e and E types, which leads to unwanted trailing 0s in the part before the exponent symbol.
Assuming your value is my_float, "{:G}".format(my_float) would print the output the way that the Python interpreter prints it. You could probably just print the number without any formatting and get the same exact result.
If your goal is to print the string representation of the float with its current precision, in non-exponentiated form, User poke describes a good way to do this by casting the float to a Decimal object.
If, for some reason, you do not want to do this, you can do something like is mentioned in this answer. However, you should set 'max_digits' to sys.float_info.max_10_exp, instead of 14 used in the answer. This requires you to import sys at some point prior in the code.
A full example of this would be:
import math
import sys
def precision_and_scale(x):
max_digits = sys.float_info.max_10_exp
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
if magnitude >= max_digits:
return (magnitude, 0)
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
scale = int(math.log10(frac_digits))
return (magnitude + scale, scale)
f = 0.0000002345E^-60
p, s = precision_and_scale(f)
print "{:.{p}f}".format(f, p=p)
But I think the method involving casting to Decimal is probably better, overall.

Problems with decimals and scientific notation in Python 2.6.6

I'm having difficulty with decimal values that I need to use for arithmetic in some cases and as strings in others. Specifically I have a list of rates, ex:
rates=[0.1,0.000001,0.0000001]
And I am using these to specify the compression rates for images. I need to initially have these values as numbers because I need to be able to sort them to make sure they are in a specific order. I also want to be able to convert each of these values to strings so I can 1) embed the rate into the filename and 2) log the rates and other details in a CSV file. The first problem is that any float with more than 6 decimal places is in scientific format when converted to a string:
>>> str(0.0000001)
'1e-07'
So I tried using Python's Decimal module but it is also converting some floats to scientific notation (seemingly contrary to the docs I've read). Ex:
>>> Decimal('1.0000001')
Decimal('1.0000001')
# So far so good, it doesn't convert to scientific notation with 7 decimal places
>>> Decimal('0.0000001')
Decimal('1E-7')
# Scientific notation, back where I started.
I've also looking into string formatting as suggested in multiple posts, but I've not had any luck. Any suggestions and pointers are appreciated by this Python neophyte.
You have to specify the string format then:
["%.8f" % (x) for x in rates]
This yields ['0.10000000', '0.00000100', '0.00000010']. Works with Decimal, too.
'{0:f}'.format(Decimal('0.0000001'))
The above should work for you
See % formatting, especially the floating point conversions:
'e' Floating point exponential format (lowercase). (3)
'E' Floating point exponential format (uppercase). (3)
'f' Floating point decimal format. (3)
'F' Floating point decimal format. (3)
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (4)
An example, using f format.
>>> ["%10.7f" %i for i in rates]
[' 0.1000000', ' 0.0000010', ' 0.0000001']
>>>
You can also use the newer (starting 2.6) str.format() method:
>>> ['{0:10.7f}'.format(i) for i in rates]
[' 0.1000000', ' 0.0000010', ' 0.0000001']
>>>
Using f-strings:
>>> rates = [0.1, 0.000001, 0.0000008]
>>> [f'{r:.7f}' for r in rates]
['0.1000000', '0.0000010', '0.0000008']
The string format {r:.7f} indicates the number of digits used after the decimal point, which in this case is 7.

How to store exponential values using python

I am looking for a way to perform a digit divided by larger value(2/5000000) and then store that value in table, but the problem is when i save that value, only 0 is stored , instead of correct value.I tried with float, double precision, but still only 0 is stored, is there any other way .
Thank you
Remember to operate on floating numbers, and not convert it after the operation. E.g. 2/5000000.
Also, use the Decimal library, if you are looking for more accurate decimals.
You need to use floating point division. To be explicit, you can cast ints to float:
>>> a = 2
>>> b = 5000000
>>> c = a/float(b)
>>> c
4e-07
You can cast either a or b to float.

Categories