This question already has answers here:
How to round values only for display in pandas while retaining original ones in the dataframe?
(1 answer)
Can a variable be used in Python to define decimal places
(3 answers)
Set Decimal Point Precision in a Pandas Dataframe
(2 answers)
Closed 8 months ago.
I've looked around and I cannot find an anwser to my question.
I need decimal formatting where the decimal can be different depending on the situation. For this situation I want to pass a variable containing the decimal value.
The values I'm getting from my pandas DataFrame are in this format 3.18e-06, which in this case needs to be turned into 8 decimals, e.g., 3.18123456
Can I either turn my pd DF into an 8 decimal based float64 or can i somehow convert 3.18e-06 into 8 decimals after grabbing it from my db?
Preferably I want to pass a variable containing the decimal for formatting.
Something like:
decimal = 0.00000001
{0:.{decimal}f}".format(a)
EDIT:
In the end, none of the suggested options did it for me. Maybe I didn't phrase my question well enough. I'll share my solution here for anyone else who might need it.
ticksize is a variable which changes depending on the Binance Trading pair you're using, it comes in a format like: 0.00001 or 0.0000001.
async def get_precision(ticksize):
a = '{:.{prec}f}'.format(ticksize, prec=15)
regex = "..(\d+1).*"
try:
b = re.match(regex, str(a))[1]
precision = len(b)
return precision
except Exception as e:
print(f'An exception has occured on get_precision - {e}')
return False
# this function returns the length of ticksize starting from the first 0 after the dot.
# Now that we have our precision we can use a string format to get what we need.
last_buy = '{:.{prec}f}'.format(a, prec=precision)
#returns: Last purchase price for XRPBTC: 0.00001588
float("8.99284722486562e-02") # 0.0899284722486562
and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02")) # '0.08992847'
Related
This question already has answers here:
How to implement conditional string formatting? [duplicate]
(3 answers)
Closed 1 year ago.
I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.
I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.
When I tried using round(3) it'll return 3.0.
Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?
Try choosing the format as a function of the values wholeness:
"{d}" if int(a) == a else "{:0:.2f}"
Can you finish from there?
You can use a conditional expression to choose the format based on the type of the variable:
for x in (33.3333333, 3):
print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
You could also implement it using a dictionary to map types to format strings:
formats = {int: "{:0}", float: "{:.2f}"}
for x in (33.3333333, 3):
print(formats.get(type(x)).format(x))
This question already has answers here:
How to round to 2 decimals with Python? [duplicate]
(21 answers)
Closed 2 years ago.
So say I have something that looks like this:
def probability_color():
if color == 'red':
return float(3/10)
so essentially it should return .30 instead of anything longer. My specific problem includes fractions that aren't as clean as this example so I'm getting very long decimal float values in this particular scenario. Is there a simple solution that would format it rather than using something like round()?
Just use the round format in Python to help.
Here is the improved code:
def probability_color():
if color == 'red':
# Decimal places :)
return float('%.2f' % (1/10))
This question already has answers here:
Python Decimals format
(6 answers)
Closed 3 years ago.
I have a python program which takes some floating type values and writes to a file.
I round these numbers to 6 decimal places and then convert to a string type before writing to file.
file.write(str(round(value,6)))
However with certain numbers the value written to file is in the format shown below.
e.g. 3e-06 or 4e-03
How can I avoid this and instead write out in decimal format like
0.000003 and 0.004000
How can I print exactly 6 figures after the decimal point.
You can use the f-string f'{value:.6f}'.
Example:
value = 0.234
print(f'{value:.6f}')
value = 1
print(f'{value:.6f}')
value = 0.95269175
print(f'{value:.6f}')
Output:
0.234000
1.000000
0.952692
Also, in the answer linked in a comment, there was reference to :g. That can work, but probably not in this situation, because g may print scientific notation where appropriate, and discards insignificant zeroes. Consider a slightly modified example using g:
value = 0.234
print(f'{value:.6g}')
value = 1
print(f'{value:.6g}')
value = 0.000000000095269175
print(f'{value:.6g}')
Output:
0.234
1
9.52692e-11
You can also use basic string formatting:
a = 3e-06
# Outputs 0.000003
print('%.6f' % a)
# Outputs 0.000003000000
print('%.12f' % a)
This question already has answers here:
Keep % format of float values
(3 answers)
Closed 4 years ago.
I initially had the columns below in string, and I converted them into float for some calculation purposes.
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.222222222222%
251.48% 23.999999999999%
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100
Growth1 Growth2
43.6546 1.2448
0.4529 0.02222222222222
2.5148 0.23999999999999
However, they are in decimal format and I want them to show in % format. But I can't just add {:,.2%}'.format after a line like:
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100(formatters=[{:,.2%}'.format])
Is there any way that you can do to keep the float in % format and round it to the 2 decimal places with the least amount of code (like 1 or 2 lines)? Thank you.
Desired output:
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.22%
251.48% 24.00% # or 23.99%, no big deal
It looks like the parameter you use for format is not correct. It should be {:,.2f}, and % outside:
Example:
>>> "{:,.2f}%".format(4365.46)
'4,365.46%'
Maybe using pandas style?
df.style.format("{:.2%}")
When you display the returned object from this call, like you normally would a dataframe, it'll have your columns formatted in the manner you've requested.
df['Growth1'] = pd.Series(['{0:.2f}%'.format(val * 100) for val in df['Growth1']], index = df.index)
The same for "Growth2" column.
Note: if you want to keep the original column, just name the new one something other than "Growth1"
This question already has answers here:
Most Pythonic way to print *at most* some number of decimal places [duplicate]
(3 answers)
Formatting floats without trailing zeros
(21 answers)
Closed 8 years ago.
I am using xlrd to read values from cells in an excel spreadsheet.
Whenever I detect a cell type = 2, then I know it is a number.
A number of 3 in cell will be returned as 3.0
And a number of 3.14 will be returned as 3.14
I will be converting numbers to text.
What function should I use to remove zeroes right of the decimal and the decimal?
The above 2 numbers should be 3 and 3.14
Use str.rstrip(), twice:
str_of_float.rstrip('0').rstrip('.')
This will remove trailing zeros, and if that leaves you with a trailing . it's removed as well.
Demo:
>>> '3.14'.rstrip('0').rstrip('.')
'3.14'
>>> '3.0'.rstrip('0').rstrip('.')
'3'
>>> '3000.0'.rstrip('0').rstrip('.')
'3000'
Don't be tempted to use .rstrip('.0'); it'll remove too many zeros:
>>> '3000.0'.rstrip('.0')
'3'
I always use format when printing values to strings. Using the format specs, it gives a good deal of control over what is printed.