Add zeros to a float after the decimal point in Python - python

I am reading in data from a file, modify it and write it to another file. The new file will be read by another program and therefore it is crucial to carry over the exact formatting
for example, one of the numbers on my input file is:
1.000000
my script applies some math to the columns and should return
2.000000
But what is currently returned is
2.0
How would I write a float for example my_float = 2.0, as my_float = 2.00000 to a file?

Format it to 6 decimal places:
format(value, '.6f')
Demo:
>>> format(2.0, '.6f')
'2.000000'
The format() function turns values to strings following the formatting instructions given.

From Python 3.6 it's also possible to do f-string formatting. This looks like:
f"{value:.6f}"
Example:
> print(f"{2.0:.6f}")
'2.000000'

I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.
foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))
output:
56.0
56.00
56.000
56.00000
Meaning that the 2nd argument of format takes the decimal places you'd have to go up to. Keep in mind that format returns string.

I've had problems with using variables in f strings. When all else fails, read the manual :)
"A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal."
https://docs.python.org/3/reference/lexical_analysis.html#f-strings
Case in point:
my_number = 90000
zeros = '.2f'
my_string = f"{my_number:,{zeros}}"
print (my_string)
90,000.00
my_string = f'{my_number:,{zeros}}'
will not work, because of the single quotes.
Quotes containing the f string and the string
variable used in the f string should be
different.
If using single quotes for the string variable,
use double quotes for the f module and vice versa.

An answer using the format() command is above, but you may want to look into the Decimal standard library object if you're working with floats that need to represent an exact value. You can set the precision and rounding in its context class, but by default it will retain the number of zeros you place into it:
>>> import decimal
>>> x = decimal.Decimal('2.0000')
>>> x
Decimal('2.0000')
>>> print x
2.0000
>>> print "{0} is a great number.".format(x)
2.0000 is a great number.

Related

How to get range of bits from byte in python? [duplicate]

I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:
Example:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
Is there a way of doing this?
Use the format() function:
>>> format(14, '#010b')
'0b00001110'
The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.
If you did not want the 0b prefix, simply drop the # and adjust the length of the field:
>>> format(14, '08b')
'00001110'
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :, so use
>>> '{0:08b}'.format(1)
'00000001'
I am using
bin(1)[2:].zfill(8)
will print
'00000001'
When using Python >= 3.6, you can use f-strings with string formatting:
>>> var = 23
>>> f"{var:#010b}"
'0b00010111'
Explanation:
var the variable to format
: everything after this is the format specifier
# use the alternative form (adds the 0b prefix)
0 pad with zeros
10 pad to a total length off 10 (this includes the 2 chars for 0b)
b use binary representation for the number
You can use the string formatting mini language (Thanks to #Martijn Pieters for the suggestion) idea:
def binary(num, length=8):
return format(num, '#0{}b'.format(length + 2))
Demo:
print(binary(1))
Output:
'0b00000001'
I like python f-string formatting for a little more complex things like using a parameter in format:
>>> x = 5
>>> n = 8
>>> print(f"{x:0{n}b}")
00000101
Here I print variable x with following formatting: I want it to be left-filled with 0 to have length = n, in b (binary) format. See Format Specification Mini-Language from previous answers for more.
Sometimes you just want a simple one liner:
binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])
Python 3
You can use something like this
("{:0%db}"%length).format(num)
You can use zfill:
print str(1).zfill(2)
print str(10).zfill(2)
print str(100).zfill(2)
prints:
01
10
100
I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable...
e.g. -
x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.
You can use string.rjust method:
string.rjust(length, fillchar)
fillchar is optional
and for your Question you can write like this
'0b'+ '1'.rjust(8,'0)
so it will be '0b00000001'

Comma as decimal point in python

I am new to python.
In python, I wish to convert float variables to string variable with 2 decimal places and decimal comma.
For example, 3.1415 --> 3,14
it works fine. But when I convert 1.20, it gives 1,2 instead of 1,20.
I want the latter one
Is there an easy way to achieve that? Thank You Guys
My code is in the following:
s=float(input())
a=round(s,2)
x=str(a)
y=x.replace('.',','))
print(y)
Try using this:
>>> num = 1.201020
>>> '{:.2f}'.format(num).replace('.', ',')
'1,20'

Python - Convert scientific notation string to float retaining decimal places

I am using python to read some float values from a file. The values read are input to an 'Ada'(Programming Language) program.
The values being read are in different formats (scientific, decimal) and I would like to retain the format.
Everything works well with simple float() operation except when converting '1.0e-5' to float.
>>float('1.0e-5')
#returns 1e-5
1e-5 when used in Ada program gives
error:negative exponent not allowed for integer literal
1.0e-35 works with ada program.
I know if I use format I can get 1.0e-5
>>>"{:.1E}".format(float('1.0e-5'))
#returns '1.0E-5'
But this changes format for other read values also as my reading/manipulation function is common.
How should I approach this problem?
and if
float('1.0')
#returns 1.0
why same behavior is not followed when converting a scientific notation string to float?
(My reading/manipulation function is common. Using formatter string will change the formatting of other read values also)
You could use a custom float to string conversion function which checks if the number will be accepted by Ada using a regular expression (which tests if there are only non-dots before the exponent character, and in which case only convert with format):
import re
def ada_compliant_float_as_string(f):
return "{:.1e}".format(f) if re.match("^-?[^\.]e",str(f)) else str(f)
for f in [-1e-5,1e-5,1.4e-5,-12e4,1,1.0]:
print(ada_compliant_float_as_string(f))
prints:
-1.0e-05
1.0e-05
1.4e-05
-120000.0
1
1.0
only the first value is corrected, other values are just the string representation of a float, unchanged.

How to properly use string formatting in Python 2.7?

Ok, please bear with me, I'm completely new to this. This is for school, and the exact syntax isn't important here for my assignment, but for my own personal knowledge I want to know a little more about string formatting.
whenever I use %f it defaults to 2 decimal places. Is there a string format that I can use on a float that will show the float with the number of decimals it actually has?
for instance my list contains 2.0, 2.01, 2.001, 2.0001 and I want to use a string format to print them as they look. Which format code would I use or how could I use %f properly if possible?
This is in Python 2.7 on Windows 7(if that matters).
%g may be what you're looking for:
>>> "%g, %g, %g, %g" % (2.1, 2.01, 2.001, 2.0001)
'2.1, 2.01, 2.001, 2.0001'
If you convert the float to a string, then when you print it, it will be displayed just as you wrote it.
>>> x = str(2.0)
>>> print(x)
2.0
>>> x = str(2.01)
>>> print(x)
2.01
>>> x = str(2.001)
>>> print(x)
2.001
>>> x = str(2.0001)
>>> print(x)
2.0001
(In fact, to be precise, in Python you're not actually converting the floating point object, but creating a string object that looks like it. But that's a bit outside of the scope of your question.)
UPDATE
Someone posted a way to remove trailing zeros from floating point numbers using the Decimal class, here: Removing Trailing Zeros in Python

Rounding decimals with new Python format function

How do I round a decimal to a particular number of decimal places using the Python 3.0 format function?
Here's a typical, useful example...:
>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'
the nested {1} takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resulting {0:.4f} then applies. Of course, you can hardcode the 4 (or whatever number of digits) if you wish, but the key point is, you don't have to!
Even better...:
>>> '{number:.{digits}f}'.format(number=p, digits=n)
'3.1416'
...instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument names, and pass the corresponding values as keyword (aka "named") arguments to format -- that can be so much more readable, as you see!!!
An updated answer based on [Alex Martelli]'s solution but using Python 3.6.2 and it's updated format syntax I would suggest:
>>> n=4
>>> p=math.pi
>>> f'{p:.{n}f}'
'3.1416'
But by choosing your variables wisely your code becomes self documenting
>>> precision = 4
>>> pi = math.pi
>>> f'{pi:.{precision}f}'
'3.1416'
In Python 3.x a format string contains replacement fields indicated by braces thus::
".... {0: format_spec} ....".format(value)
The format spec has the general layout:
[[fill]align][sign][pad][width][,][.precision][type]
So, for example leaving out all else but width, precision and type code, a decimal or floating point number could be formatted as:
>>>print("The value of pi is {0:10.7f} to 7 decimal places.".format(math.pi))
This would print as:
The value of pi is 3.1415927 to 7 decimal places.
To round x to n decimal places use:
"{0:.{1}f}".format(x,n)
where 0 and 1 stand for the first and second arguments of the str.format() method, respectively.
I just found out that it is possible to combine both the {0} and the {digits} notation. This is especially useful when you want to round all variables to a pre-specified number of decimals with 1 declaration:
sName = 'Nander'
fFirstFloat = 1.12345
fSecondFloat = 2.34567
fThirdFloat = 34.5678
dNumDecimals = 2
print( '{0} found the following floats: {1:.{digits}f}, {2:.{digits}f}, {3:.{digits}f}'.format(sName, fFirstFloat, fSecondFloat, fThirdFloat, digits=dNumDecimals))
# Nander found the following floats: 1.12, 2.35, 34.57
=============================================================
EDIT:
Since all answers (including mine) where using the 'old' {0}.format() method, I'm now adding the new f-strings method (Formatted String Literals, Python 3.6+ I think) too:
x = 1.2345
y = 23.45678
print(f'x = {x:.2f} and y = {y:.2f}')
#x = 1.23 and y = 23.46

Categories