I have a list of floats in Python and when I convert it into a string, I get the following
[1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
These floats have 2 digits after the decimal point when I created them (I believe so),
Then I used
str(mylist)
How do I get a string with 2 digits after the decimal point?
======================
Let me be more specific, I want the end result to be a string and I want to keep the separators:
"[1883.95, 1878.33, 1869.43, 1863.40]"
I need to do some string operations afterwards. For example +="!\t!".
Inspired by #senshin the following code works for example, but I think there is a better way
msg = "["
for x in mylist:
msg += '{:.2f}'.format(x)+','
msg = msg[0:len(msg)-1]
msg+="]"
print msg
Use string formatting to get the desired number of decimal places.
>>> nums = [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
>>> ['{:.2f}'.format(x) for x in nums]
['1883.95', '1878.33', '1869.43', '1863.40']
The format string {:.2f} means "print a fixed-point number (f) with two places after the decimal point (.2)". str.format will automatically round the number correctly (assuming you entered the numbers with two decimal places in the first place, in which case the floating-point error won't be enough to mess with the rounding).
If you want to keep full precision, the syntactically simplest/clearest way seems to be
mylist = list(map(str, mylist))
map(lambda n: '%.2f'%n, [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001])
map() invokes the callable passed in the first argument for each element in the list/iterable passed as the second argument.
Get rid of the ' marks:
>>> nums = [1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
>>> '[{:s}]'.format(', '.join(['{:.2f}'.format(x) for x in nums]))
'[1883.95, 1878.33, 1869.43, 1863.40]'
['{:.2f}'.format(x) for x in nums] makes a list of strings, as in the accepted answer.
', '.join([list]) returns one string with ', ' inserted between the list elements.
'[{:s}]'.format(joined_string) adds the brackets.
str([round(i, 2) for i in mylist])
Using numpy you may do:
np.array2string(np.asarray(mylist), precision=2, separator=', ')
Related
I have a set of numbers and I need to generate a string-hash that is sortable for these numbers. The numbers can be integers or floats, for example:
-5.75E+100
-4
-1.74E-101
1.74E-101
5
9
11
52.3
5.75E+100
I think to do non-exponents for integers and floats it would be simple:
# whatever the padding needs to be
>>> sorted(map(lambda x: str(x).zfill(10), [-4, 5, 52.3]))
['-000000004', '0000000005', '00000052.3']
However, what would be a more comprehensive way to generate a string-hash here that would sort properly for the above list of numbers? I am fine prepending exponents, if necessary (or converting everything to an exponent, if required), and encoding negative numbers in complement code, if that's required too.
Every float object has a built-in function hex() that will convert it to a hex string. That's almost enough to make a sortable string, but there are a few problems.
First, negative numbers have a leading - but positive numbers don't have anything. You need to add a leading character to positive numbers.
Second, - comes after + in the sorting order. You need to replace one or the other to make the order correct.
Third, the exponent comes at the end of the string. It needs to get moved to the front of the string to make it more significant, but the sign needs to stay at the absolute front.
Fourth, the exponent is a variable number of digits. It needs to be zero filled so that it has a consistent size.
Putting it all together produces something like this:
def sortable_string(number):
hex_num = float(number).hex()
if not hex_num.startswith('-'):
hex_num = '+' + hex_num
hex_num = hex_num.replace('-', '!')
hex_parts = hex_num.split('p')
exponent = hex_parts[1][0] + hex_parts[1][1:].ljust(4, '0')
return hex_parts[0][0] + exponent + hex_parts[0][1:]
You can try this,
nums = sorted(map(eval, data))
nums = list(map(str, nums))
nums
Output -
['-5.75E+100', '-4', '-1.74E-101', '1.74E-101', '5', '52.3', '5.75E+100']
import math
a = math.sqrt(25)
print(a)
My output is 5.0, how can I get a 5 (whole number) instead?
You have to check and explicitly convert to integer:
if x == (y := int(x)):
x = y
Or, without the assignment operator:
if x == int(x):
x = int(x)
As of python 3.8, you can use math.isqrt:
math.isqrt(25)
Keep in mind that this will always return an integer, even if the input is not a perfect square.
In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:
import math
a = math.sqrt(25)
a = int(a) if int(a)==a else a
print(a)
It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?
For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:
print("{:.0f}".format(a))
What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.
This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.
For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).
I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 → 5.00, 5.5 → 5.50, etc). How can I do this in Python?
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
f-string formatting:
This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.
>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!
You can see in this example we format with decimal places in similar fashion to previous string formatting methods.
NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.
Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.
String Formatting:
a = 6.789809823
print('%.2f' %a)
OR
print ("{0:.2f}".format(a))
Round Function can be used:
print(round(a, 2))
Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.
b = round(a, 2)
print(b)
Use round() - mostly for display purpose.
String formatting:
print "%.2f" % 5
If you actually want to change the number itself instead of only displaying it differently use format()
Format it to 2 decimal places:
format(value, '.2f')
example:
>>> format(5.00000, '.2f')
'5.00'
Using python string formatting.
>>> "%0.2f" % 3
'3.00'
Shortest Python 3 syntax:
n = 5
print(f'{n:.2f}')
In Python 3
print(f"{number:.2f}")
A shorter way to do format.
I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:
Python 3:
>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict)
0.12_0.13
I faced this problem after some accumulations. So What I learnt was to multiply the number u want and in the end divide it to the same number. so it would be something like this: (100(x+y))/100 = x+y if ur numbers are like 0.01, 20.1, 3,05.
You can use number * (len(number)-1)**10 if your numbers are in unknown variety.
If you want to get a floating point value with two decimal places limited at the time of calling input,
Check this out ~
a = eval(format(float(input()), '.2f')) # if u feed 3.1415 for 'a'.
print(a) # output 3.14 will be printed.
Using Python 3 syntax:
print('%.2f' % number)
I have a string of numbers with no whitespaces like this:
s = '12.2321.4310.85'
I know that the format for each number is F5.2 (I am reading the string from a FORTRAN code output)
I need to obtain the following list of numbers based on s:
[12.23,21.43,10.85]
How can I do this in python?
Thanks in advance for any help!
Slice the string into chunks of 5 characters. Convert each chunk to float.
>>> [float(s[i:i+5]) for i in range(0, len(s), 5)]
[12.23, 21.43, 10.85]
If you are really sure of the format, and that will always be handed in that way then using a step of 5 in your loop might work:
s = '12.2321.4310.85'
output = []
for i in range(0,len(s),5):
output.append(float(s[i:i+5]))
print(output)
Output:
[12.23, 21.43, 10.85]
I think the safest way is to rely on . points. Because we know that every floating point should have one fraction and always there are two fraction numbers (there might be values like 1234.56 and 78.99 in the data that generates s = "1234.5678.99"). But we are not sure how many digits are before .. So we can extract values one by one based on ..
s = '12.2321.4310.85'
def extractFloat(s):
# Extracts the first floating number with 2 floatings from the string
return float( s[:s.find('.')+3]) , s[s.find('.')+3:]
l = []
while len(s) > 0:
value, s = extractFloat(s)
l.append(value)
print(l)
# Output:
# [12.23, 21.43, 10.85]
>>> num = int('0241034812')
>>> print(num)
241034812
>>>
In the above code, I'm setting the variable num to 0241034812; however, when I print the variable it deletes the first zero.
Why is this happening?
Integers are stored/displayed as a "normal" number, not the string value. If you want to display the number prefixed with zeroes you can do that when displaying the variable.
You can use the following syntax to add leading zeros to an integer:
print "%010d" % (241034812,)
The example above will display the integer 241034812 with 10 digits as 0241034812.
I'm setting the variable 'num' to '0241034812'
No, you're setting it to 241,034,812: an integer value, about two hundred forty million. If you want to set it to '0241034812', you should use a string rather than an integer. That is, you should drop the call to int:
>>> num = '0241034812'
>>> print(num)
0241034812
>>>
If you're storing some number in a format where a leading zero would be useful/significant (maybe a barcode, ISBN, or the like), you can re-add them when converting back into a string using .format
>>> num = int('0241034812')
>>> print('{:010d}'.format(num))
0241034812
Briefly, the first 0 in the format spec means to add leading zeros if not present to fill 10 (the 10) characters.
You wanted to print your integer to a specific zero-padded width, use string formatting. The format() function, for example:
>>> num = 241034812
>>> print(format(num, '010d'))
0241034812
or print the original string from which you parsed the integer in the first place.
Integers do not store a 'print width' or any number of leading 0 digits.