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)
Related
This question already has answers here:
How can I format a decimal to always show 2 decimal places?
(13 answers)
Closed 3 months ago.
i want to round off a float to 3 dp in python with 00 in the end if the float don't have 3 dp
like 15.4 into 15.400
thank you.
programme:
x=round(15.4)
result:
15.400
The "rounding" you are talking about can only be done if you convert the float to a string. This is usually only done for display purposes. In this case you can use a so-called f-string to do this formatting:
x = 15.4
print(f"{x:.3f}")
Hello its pretty simple you can do something like this
a=15.4
b=("%.3f" % a)
print(b)
15.4 and 15.400 are the same number. round() returns a number. What you want is to have a different representation when you convert it to a string.
You need to do string formatting. Just copying the other answers here, there are two ways.
f-strings:
n = 15.4
n_str = f"{n:.3f}"
%-formatting:
n_str = "%.3f" % n
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'
This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 6 years ago.
i'd like to convert a decimal to a string, where zeros at the end are preserved.
Using str method erases the last zeros.
Example:
number=0.20
Goal: "0.20"
e.g. using: str(number)="0.2" doesn't seem to work.
If you want 2 decimal places use:
number = 0.20
str_number = '%.2f' % number
Number before f indicates the desired number of places.
This can be done using string formatting.
"{0:.2f}".format(number)
Will return 0.20.
Doing your chosen method won't work because upon declaring number = 0.20 it omits the last zero right away. If you put that into your idle:
number = 0.20
number
0.2
So declaring number as str(number) is doing str(0.2).
Use the % operator with an appropriate format string:
'%1.2f' % number
=> '0.20'
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.
This question already has answers here:
Limiting floats to two decimal points
(35 answers)
Closed 5 months ago.
I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using float() to convert a line into a float, and raising a ValueError if that fails. I am storing all floats in a list. When printing it out, I'd like to print it out as a 2 decimal places floating point.
Assume I have a text file with the numbers -3.65, 9.17, 1. I read each one, and once I convert them to float and append them to a list. Now in Python 2, calling float(-3.65) returns -3.65. In Python 3 however, float(-3.65) returns -3.6499999999999999 which loses its precision.
I want to print the list of floats, [-3.6499999999999999, 9.1699999999999999, 1.0] with 2 decimal points only. Doing something along the lines of '%.1f' % round(n, 1) would return a string. How can I return a list of all two decimal points of floats, and not strings? So far, I rounded it using [round(num, 2) for num in list] but would need to set the decimal points / precision instead of round().
The comments state the objective is to print to 2 decimal places.
There's a simple answer for Python 3:
>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'
or equivalently with f-strings (Python 3.6+):
>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'
As always, the float value is an approximation:
>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'
I think most use cases will want to work with floats and then only print to a specific precision.
Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.
The simple way to do this is by using the round buit-in.
round(2.6463636263,2) would be displayed as 2.65.
In a word, you can't.
3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.
The difference between (older?) Python 2 and 3 is purely due to the default formatting.
I am seeing the following both in Python 2.7.3 and 3.3.0:
In [1]: 3.65
Out[1]: 3.65
In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
For an exact decimal datatype, see decimal.Decimal.
Try this:
num = input("Please input your number: ")
num = float("%0.2f" % (num))
print(num)
I believe this is a lot simpler. For 1 decimal place use %0.1f. For 2 decimal places use %0.2f and so on.
Or, if you want to reduce it all to 2 lines:
num = float("%0.2f" % (float(input("Please input your number: "))))
print(num)
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!