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

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

Related

How to display last 2 digits from a number in Python

I am trying to take air pressure readings and plot them with their last 2 digits showing. However, when I use modulo:
--> x = 1004
--> x % 100
--> 4
This just generates 4.
How can I display this to show 04 instead of 4?
Thanks!
Try the following:
str(x%100).zfill(2)
If you need it as an int or a float, I don't think this is possible. If it's only for display purposes, convert it to a string and take the last 2 characters:
x = 1004
>>> str(x)[-2:]
'04'
If you just print out a number, it prints it out in its default format. For the number 2, that's obviously going to be 2, not 02.
If you want to specify a custom format, you need to use some form of string formatting. Python has a few ways to do it.
Format Strings
The same Format String Syntax is used by the format function, the str.format method, Formatter subclasses, and (with slight differences that aren't relevant here) f-string literals.
You can specify a width of 2, plus an align of = (meaning numeric alignment—padding is placed after any + or -) and a fill of 0. But there's also a special shortcut, where placing a 0 right before the width means numeric-aligned zero-fill. So:
>>> f"{x % 100:02}"
'02'
>>> format(x % 100, '02')
'02'
>>> '{:02}'.format(x % 100)
'02'
printf-style String Formatting
Python has an older, but still sometimes useful, way to do formatting,1 which more closely matches that of C and similar languages, calling printf-style or %-formatting.
You specify a width of 2, and a flag of 0, which indicates numeric zero-padding, together with a type of d to specify that you want to format the number as a signed integer decimal:
>>> "%02d" % (x % 100,)
'02'
While %-formatting isn't as flexible and powerful as format strings, it can sometimes be simpler to understand (especially if you're used to C or another language), is often faster, and works with bytes as well as str.
Manual string operations
Finally, you can always convert the number to a string and then use string methods on it. For example, you can use the zfill method to zero-fill a string:
>>> str(x % 100).zfill(2)
'02'
… or you can use the rjust method to right-justify it with '0' as a fill character:
>>> str(x % 100).rjust(2, '0')
'02'
In fact, instead of calculating the remainder, you could just convert the whole thing to a string, truncate it, then zero-fill:
>>> str(x)[-2:].zfill(2)
… although this probably won't be what you want is x is, say, -123 (you'll get 23 instead of 77).
1. In fact, it provides two older solutions, the other being template strings, but these aren't useful as often.
The shortest way to do this is '%02d' % (x % 100)
x = 1004
x = x % 100
str(x)
y = len(x)
if y == 0:
end
elif y == 2:
print (x)
elif y == 1:
print ('0'x)
else:
x = str(x)[-2:]
print (x)
In this, I've converted it into a string & calculated the length of the value as 'y'. Using a basic [if elif else] structure I have returned the values in your format, but as strings.
It is unclear what you wanted to use these values for because if you want them to represent figures you will probably need to edit the settings of whatever output application you are using. An alternative solution would be to use the value for 'x' as being different to the string so that the number value can still be used regardless of the way it is displayed when printing. wink, wink.
You could use string formatting too.
ans = 1004 % 100
format(ans, '03d')
More information about String formatting can be found here: https://pyformat.info/
No modulo, no zfill.
"{:02d}".format(12345)[-2:]
#> 45
"{:02d}".format(0)[-2:]
#> 00
"{:02d}".format(-9876)[-2:]
#> 76
"{:02d}".format(-1)[-2:]
#> -1
Your first step to use the modulus operator to find the two-least significant digits is correct.
Then you'll want to use a format string to pad your result when printing it. See: Python format Integer into fixed length strings

printf type formating in Python is not returning expected result

I want to embed the numerical variable inside the string with 2 decimal digits.
The code is the following:
x = 121.37890
print("The variable x has the value %.2d, which is surprising" % x)
It returns:
The variable x has the value 121, which is surprising
What I am doing wrong?
See reference of String format mini language
wich tells you what the specifier inside the formatting part are for. d for
Decimal Integer. Outputs the number in base 10.
integer-like numbers without digits, f for
Fixed point. Displays the number as a fixed-point number. The default precision is 6.
# python 2.x - discouraged to use it
print("The variable x has the value %.2f, which is surprising" % x)
# explicit format syntax
print("The variable x has the value {:.2f}, which is surprising".format(x))
#implicit format syntax
print(f'The variable x has the value {x:.2f}, which is surprising')
Output:
The variable x has the value 121.38, which is surprising
See PEP-0498 for formatting in literal string interpolation (implicit fromat syntax).
A comparison of old vs. new syntax can be viewed in the docs https://docs.python.org/3.1/library/string.html#format-examples - it still works but you should switch using explicit / implicit formatting.
Further reading: Python string formatting: % vs. .format
Make it like
print("The variable x has the value %.2f, which is surprising" % x)
you have to use "fixed-point" instead of "decimal" in formatting.
returns:
The variable x has the value 121.38, which is surprising

fixed field width for float python [duplicate]

I read a lot of discussion about this on SE, but still can't find the right one.
I want to plot some numbers, of various lengths, with the same number of digits.
For example I have: 12.345678, 1.2345678. Now, since I have to plot them with their error, I want that each one has a different format, in order that they are significant.
So, I want to plot them with a variable number of decimals. In my case, it makes no sense to plot 23.45678+/-1.23456 but better is 23.4+/-1.2. On the other hand, I need that 1.234567+/-0.034567 becomes 1.23+/-0.03.
So, let's say, I want to plot all the numbers with a fixed width, could be 3 digits in total plus the comma. I should use something like '%1.1f' %num, but I can't find the right way. How can I do that?
I recommend defining a class that interprets a string formatter to give what you want.
Inside that class, you determine the length of the integer portion of your float and use that to define the appropriate string format.
In a nutshell, the class creates a formatter like '{:4.1f}' if your input is 12.345 (because you have two digits before the decimal separator) and {:4.2f} if your input it 1.2345 (because you have only one digit before the decimal separator). The total number of digits (4in this example) is provided as an input.
The new formatter is: {:nQ} where n is the total number of digits (so in the above example, you'd specify {:4Q}to get the output you want.
Here's the code:
import math
class IntegerBasedFloat(float):
def __format__(self, spec):
value = float(self)
# apply the following only, if the specifier ends in Q
# otherwise, you maintain the original float format
if spec.endswith('Q'):
# split the provided float into the decimal
# and integer portion (for this math is required):
DEC, INT = math.modf(value)
# determine the length of the integer portion:
LEN = len(str(abs(int(INT))))
# calculate the number of available decimals
# based on the overall length
# the -1 is required because the separator
# requires one digit
DECIMALS = int(spec[-2]) - LEN - 1
if DECIMALS < 0:
print 'Number too large for specified format'
else:
# create the corresponding float formatter
# that can be evaluated as usual:
spec = spec[-2] + '.' + str(DECIMALS) + 'f'
return format(value, spec)
DATA = [12.345, 2.3456, 345.6789]
print '{:4Q}'.format(IntegerBasedFloat(DATA[0]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[1]))
print '{:4Q}'.format(IntegerBasedFloat(DATA[2]))
print 'This is a "custom" float: {:5Q} and a "regular" float: {:5.3f}'.format(IntegerBasedFloat(12.3456),12.3456)
The output should be:
12.3
2.35
346
This is a "custom" float: 12.35 and a "regular" float: 12.346
This answer is inspired by:
- splitting a number into the integer and decimal parts in python
- Add custom conversion types for string formatting

Format number in python with leading zeros and fixed decimal places

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)

How to retain leading zeros of int variables?

Below is a section of code which is part of a functional decryption and encryption program.
while checkvar < maxvar: # is set to < as maxvar is 1 to high for the index of var
#output.append("%02d" % number)
i =ord(var[checkvar]) - 64 # Gets postional value of i
i = ("%02d" % i)
if (checkvar + 1) < maxvar:
j =ord(var[(checkvar + 1)]) - 64 # Gets postional value of i
j = ("%02d" % j)
i = str(i) + str(j) #'Adds' the string i and j to create a new i
li.append(int(i))
checkvar = checkvar + 2
print li
As you can see the two variables i and j are first treated as string to add a 0 in front of any single digit numbers (as string). These variables then are combined to make a four digit number (still as a string). Later in the program the number created are used in a pow() function, as ints remove any leading zeros.
My question: Is it possible to force python to keep the leading zero for ints? I have and continued to search online.
Edit
To help people I have included the encryption part of the program. This is where the problem lies. The variables created in the above code are passed through a pow() function. As this can't handle strings I have to convert the variables to ints where the leading zero is lost.
#a = li[]
b=int(17)#pulic = e
c=int(2773)#=n
lenli=int(len(li))
enchecker = int(0)
#encrpted list
enlist = []
while enchecker < lenli:
en = pow(li[enchecker],b,c)#encrpyt the message can only handle int
enlist.append(int(en))
enchecker = enchecker + 1
print enlist
Though the comments above are true regarding 1, 01, and 001, are all the same as an int, it can be very helpful in temporal modeling, or sequential movie making to maintain the leading zeros. I do it often to ensure movie clips are in proper order. The easy way to do that is using zfill() to ensure the str version of the number has at least the number of characters you tell it, and does so by filling in the left-side of the string "number" with zeros.
>>> x = int(1)
>>> NewStringVariable = str(x).zfill(3)
>>> print NewStringVariable
001
>>> NewStringVariable = str(x).zfill(5)
>>> print NewStringVariable
00001
The concept of leading zeros is a display concept, not a numerical one. You can put an infinite number of leading zeros on a number without changing its value. Since it's not a numeric concept, it's not stored with the number.
You have to decide how many zeros you want when you convert the number to a string. You could keep that number separately if you want.
I was getting date strings in the format of hhmmss coming from the serial line of my Arduino.
Suppose I got s = "122041"; this would be 12:20:41, however 9am would be 090000.
The statement print "%d" % (s) provokes a run time error because the 9 is not an octal number and is hence an illegal character.
To fix this problem:
print "%06d" % (int(s))
Try this:
number = 1
print("%02d" % (number,))
or:
print("{:02d}".format(number))
The explanation of "%02d":
% - This tells the interpreter that a variable should be inserted here.
02 - This tells the interpreter to expect the variable to be 2 in length.
d - This tells the interpreter to expect a number, or should we say a"'d’igit".

Categories