Format number in python with leading zeros and fixed decimal places - python

I am trying to format a number into a string in python. The result I hope for is for 0.1423 to be converted to 000.14. I tried
num = 0.1423
print '%0.2f' %num
But this just results in the 0.14. I can't seem to get the leading zeros.
Cheers,
James

num = 0.1423
print '%06.2f' %num
The six indicates the total field width and includes the decimal point. The zero indicates include leading zeros, the 2 indicates the precision.

The field width has to be provided as well to get the required number of leading zeros:
print "%06.2f" % num
Output:
000.14

use str.format
print "{:06.2f}".format(num)

Related

Formatting Number With Comma

I am trying to put comma's on a number without striping any numbers after the decimal point.
number
12018093.1000
results
12,018,093.10
I tried this code but it strips away the last 0 which I don't know why.
rps_amount_f = ("{:,}".format(float(rps_amount_f)))
I'm not sure why the zeros are stripped away in your example, although this may be a solution using an f-string:
rps_amount_f = 12018093.1
rps_amount_f_str = f"{rps_amount_f:,.10f}"
Here '10' before the f is the decimal precision you want to have in the string, i.e. 10 decimals in this case.
You said that you only want one zero so really isn't the solution just to add a 0 to the end of the string? Anyway here's my solution:
if("." in str(rps_amount_f)):
rps_amount_f = ("{:,}".format(float(rps_amount_f)) + "0")
else:
rps_amount_f = ("{:,}".format(float(rps_amount_f)))
If you want two decimal places you just get rid of the if statement and round it.
print("{:,.4f}".format(float(rps_amount_f))) # 12,018,093.1000
https://docs.python.org/3/library/string.html#format-specification-mini-language

Trunc a number and get removed value. Or cast to int?

I try to get the removed part of the math.trunc function.
Or a function supports this request.
import math
number = 1.9
newnumber, removed = math.trunc(number)
I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.
Obove example will not work :/
Any suggestions ?
You need to keep a handle on the truncated number, and subtract it from the original number:
import math
number = 1.9
truncated = math.trunc(number)
print(truncated, number - truncated)
If you use modf you can flip the order of your variables and get the result you want.
import math
number = 1.9
removed, newnumber = math.modf(number)
For a starting point, use modulus 1 get the removed part.
def truncate(n):
return math.trunc(n), n % 1
Then you want to consider how negative numbers are handled. Do they return a positive ‘removed’ value?
This method won’t work for negative numbers, instead you can subtract the truncates number from the original:
t = math.trunc(n)
return t, n - t

How can I convert a float in a str without losing significant figures?

I want to convert the number 0.054000 in a str, but when I write srt(0.054000) I get '0.054'. I need to get '0.054000'. How can I do it?
I have a data file with numbers as my example (0.054000). I need to count the digits of each number. I don't know how to read that number in a way that I count seven digits, for instance.
I think that Dan Patterson's method is the only way to do it reliably - python makes no differentiation between .0054 and .054000: e.g.
>>> .0054 is .0054000
True
Thus you will probably have to simply specify the number of digits you have in sig figs, either using his method or (str(.0054000) + "0"*number_of_sig_figs).
A format specifier starts with a colon and then may contain any of the terms shown
in brackets in the following (each of the terms is optional)
: [[fill]align] [sign] [#] [0] [width] [,] [.precision] [type]
A brief description of the [.precision] is provided below.
.precision: Maximum number of characters for strings (integer); number of digits of
precision for floats. For f, F, e, and E type specifiers this is the number
of digits to the right of the decimal point.
We can use this to specify the precision of our float value:
a=0.540000
print("{:06f}".format(a))
This gives the desired output:
0.540000
Hope this was helpful!

How do I preserve leading zeros in Python integers for string formatting

I have what I believe to be a simple question. I have the following code and the output is not what I expect:
import socket
import time
r=031508.78
h=373309.9
z=0
mes='"TSRA %s %s %s\r\n"'%(r,h,z)
print mes
My problem is that r prints as '31508.78' and I want '031508.78'. How I get preserve the leading zero?
The 0 in front of the number is not important for python, because numbers have no leading 0s. You can use:
print '%09.2f'%r
I prefer the new string format mini language. I find it more intuitive.
r = 31508.78
h = 373309.9
z = 0
print '"TSRA {0: 011.3f} {1: 011.3f} {2}"\r\n'.format(r, h, z)
print '{0: 011.3f}\n{1: 011.3f}\n{2: 011.3f}'.format(r, h, z)
{0: 011.3f} 0: indicates the first item (r). 011 tells the formatter that there will be 11 characters including the decimal point and a place holder for a negative sign. By placing a 0 in front the formatter will pad the space with leading zeros. Finally, .3f indicates the precision and a fixed number of places after the decimal point.
Yields:
"TSRA 031508.780 373309.900 0"
031508.780
373309.900
000000.000
I don't think there is any way to store a number with a leading zero in python.
This leaves you with two ways:
1) Make r a string i.e. r="031408.78"
I think this is the best method for you as you can do all the arithmetic you want to do (using the implicit typecasting of python) and see the number appended with a 0 wherever you use it.
2) If you simply want to print the number with leading zeros consider using this
print "%09.2f' % r #for this you need the length of the number
For Python, there is no difference in the following things:
31508.78
031508.78
0000000031508.78
31508.7800000000000
0000000000000031508.7800000000000
Those are all valid representations of the exact same number, which is canonically represented by 31508.78, which is essentially just a convention. Different representations are possible too, and actually, the number is represented in a way that’s described by the IEEE-754 standard.
So, when you want that leading zero, you have to tell Python explicitely to put it there because it simply doesn’t know about it. You just used one of many valid representations to specify that one number which default string representation does not include leading zeroes.
The best way to do this is using string formatting, which comes in two flavors. The old style flavor, using the % operator, and the newer str.format function:
>>> '%09.2f' % 31508.78
'031508.78'
>>> '{:09.2f}'.format(31508.78)
'031508.78'
Or, if you don’t actually want a number, you could also just specify the number as a string to begin with, which of course keeps the leading zero.

Python, want to print float in exact format +-00.00

I need to format a float to the format +-00.00, tried the basic string formatting but can't get the leading + or - sign or two leading 0s if the value is fractional, any pointers?
'%+06.2f' % 1.1123344
+ means always use sign
0 means zero fill to full width.
6 is the total field width including sign and decimal point
.2 means 2 decimals.
f is float
Use '%+06.2f' to set the width and precision appropriately. The equivalent using new-style format strings is '{:+06.2f}'.format(n) (or '{0:+06.2f}' if your version of Python requires the positional component).
Using this should do it
x = 50.4796
a = -50.1246
print " %+2.2f" % (x)
print " %+2.2f" % (a)
The following should print
+50.48
-50.12

Categories