How to place a number in the middle of string using python? - python

suppose a float number x=3.1234. I want to print this number in the middle of the string containing space in the left side and right side of x. string length will be variable. Precision of x will be variable. if string length=10 and precision=2 the output will be " 3.14 " Have any function in python that can return this?

This is really nicely documented at https://docs.python.org/3.6/library/string.html#format-specification-mini-language
But since you clearly didn't have time to google for it:
>>> x = 3.1234
>>> length=10
>>> precision=2
>>> f"{x:^{length}.{precision}}"
' 3.1 '
I'm afraid your notion of precision doesn't agree with Python's in the default case. You can fix it by specifying fixed point formatting instead of the default general formatting:
>>> f"{x:^{length}.{precision}f}"
' 3.12 '
This notation is more perspicuous than calling the method str.format(). But in Python 3.5 and earlier you need to do this instead:
>>> "{x:^{length}.{precision}f}".format(x=x, length=length, precision=precision)
But no amount of fiddling with the format is going to make 3.1234 come out as 3.14. I suspect that that was an error in the question, but if you really meant it, then there is no alternative but adjust the value of x before formatting it. Here is one way to do that:
>>> from decimal import *
>>> (Decimal(x) / Decimal ('0.02')).quantize(Decimal('1'), rounding=ROUND_UP) * Decimal('0.02')
Decimal('3.14')
This divides your number into a whole number of chunks of size 0.02, rounding up where necessary, then multiplies by 0.02 again to get the value you want.

Related

Answer is only printing .0 instead of .00 in python [duplicate]

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)

How can I check the length of a long float? Python is truncating the length [duplicate]

I have some number 0.0000002345E^-60. I want to print the floating point value as it is.
What is the way to do it?
print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.
Like this?
>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754
As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.
Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.
You could also use decimal to not lose the precision due to binary float truncation:
>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
You can use decimal.Decimal:
>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'
This is the actual value of float created by literal 0.0000002345e-60. Its value is a number representable as python float which is closest to actual 0.0000002345 * 10**-60.
float should be generally used for approximate calculations. If you want accurate results you should use something else, like mentioned Decimal.
If I understand, you want to print a float?
The problem is, you cannot print a float.
You can only print a string representation of a float. So, in short, you cannot print a float, that is your answer.
If you accept that you need to print a string representation of a float, and your question is how specify your preferred format for the string representations of your floats, then judging by the comments you have been very unclear in your question.
If you would like to print the string representations of your floats in exponent notation, then the format specification language allows this:
{:g} or {:G}, depending whether or not you want the E in the output to be capitalized). This gets around the default precision for e and E types, which leads to unwanted trailing 0s in the part before the exponent symbol.
Assuming your value is my_float, "{:G}".format(my_float) would print the output the way that the Python interpreter prints it. You could probably just print the number without any formatting and get the same exact result.
If your goal is to print the string representation of the float with its current precision, in non-exponentiated form, User poke describes a good way to do this by casting the float to a Decimal object.
If, for some reason, you do not want to do this, you can do something like is mentioned in this answer. However, you should set 'max_digits' to sys.float_info.max_10_exp, instead of 14 used in the answer. This requires you to import sys at some point prior in the code.
A full example of this would be:
import math
import sys
def precision_and_scale(x):
max_digits = sys.float_info.max_10_exp
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
if magnitude >= max_digits:
return (magnitude, 0)
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
scale = int(math.log10(frac_digits))
return (magnitude + scale, scale)
f = 0.0000002345E^-60
p, s = precision_and_scale(f)
print "{:.{p}f}".format(f, p=p)
But I think the method involving casting to Decimal is probably better, overall.

Can Decimal('5E+1') be simply converted to Decimal('50') in Python?

Context
We display percentage values to agents in our app without trailing zeros (50% is much easier to quickly scan than is 50.000%), and hitherto we've just used quantize to sort of brute force normalize the value to remove trailing zeros.
This morning I decided to look into using Decimal.normalize instead, but ran into this:
Given the decimal value:
>>> value = Decimal('50.000')
Normalizing that value:
>>> value = value.normalize()
Results in:
>>> value
Decimal('5E+1')
I understand the value is the same:
>>> Decimal('5E+1') == Decimal('50')
True
But from a non-technical user's perspective, 5E+1 is basically meaningless.
Question
Is there a way to convert Decimal('5E+1') to Decimal('50')?
Note
I'm not looking to do anything that would change the value of the Decimal (e.g., removing decimal places altogether), since the value could be e.g., Decimal('33.333'). IOW, don't confuse my 50.000 example as meaning that we're only dealing with whole numbers.
For the purposes of output formatting, you can print your normalized Decimal objects with the f format specifier. (While the format string docs say this defaults to a precision of 6, this does not appear to be the case for Decimal objects.)
>>> print('{:f}%'.format(decimal.Decimal('50.000').normalize()))
50%
>>> print('{:f}%'.format(decimal.Decimal('50.003').normalize()))
50.003%
>>> print('{:f}%'.format(decimal.Decimal('1.23456789').normalize()))
1.23456789%
If for some reason, you really want to make a new Decimal object with different precision, you can do that by just calling Decimal on the f format output, but it sounds like you're dealing with an output format problem, not something you should change the internal representation for.
>>> Decimal('{:f}'.format(Decimal('5E+1')))
Decimal('50')
>>>
>>> Decimal('{:f}'.format(Decimal('50.000').normalize()))
Decimal('50')
>>> Decimal('{:f}'.format(Decimal('50.003').normalize()))
Decimal('50.003')
>>> Decimal('{:f}'.format(Decimal('1.23456789').normalize()))
Decimal('1.23456789')
according to the python 3.9 docs the below is how to do it - https://docs.python.org/3.9/library/decimal.html#decimal-faq
def remove_exponent(d):
return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Add Decimal(0) to your result.
Decimal('50.000').normalize()
# Decimal('5E+1')
Decimal('50.000').normalize() + Decimal(0)
# Decimal('50')

formatting in python 2.7.12

I am a beginner python programmer and I have learnt the format specifiers in the print statement.so, %3f will mean that the width of the floating point number should be 3.
But,in the following code,output is not like that
import math
print "%3f"%(math.pi)
this code should output 3.1 because we specified the width as 3.
but the output is 3.141593.
My questions:
1.Does specifying only width work for integers and not for floating point numbers?
2.is it must to specify both width and precision while formatting floating point numbers?
Specifying only width works also for floating point numbers. The thing is that the width includes decimal points too. For example, doing:
"%10f" % math.pi # ' 3.141593'
As you can see, the string is 10 characters long. Another thing to take into account here is that by default, python will output 6 decimal points, so doing "%3f" is the same as "%3.6f".
>>> "%3f" % math.pi
'3.141593'
>>> "%3.6f" % math.pi
'3.141593'
>>>
That's why you are not getting your expected output '3.1'. To get that, and knowing the previous concepts you should specify:
"%3.1f" % math.pi
Or just:
"%.1f" % math.pi
I'd just specify the part after the decimal point like this:
>>> print "%.1f"%(math.pi)
3.1
You should also try the arguably better .format method. It offers much more clarity and functionality while formatting. This is will do what you need,
'{:.1f}'.format(math.pi)
You can also specify padding width,if needed, easily like,
'{:6.1f}'.format(math.pi)
You can read up more here https://pyformat.info/
>>> print "%3f" % x
99999.454540
>>> print "%.3f" % x
99999.455
Well the first one in %30.1%f specifies the length of the string/
>>> print "%30.1f" % x
99999.5
Look at this!
>>> print "%.1f" % x
99999.5
See the last one? It has it rounded off. If you don't want to round off then use decimal instead of float.
import math
from decimal import *
getcontext().prec=6
value = Decimal('999.559987').quantize(Decimal('.01'), rounding=ROUND_DOWN)
print str(value)
print '%.2f' % 999.559987
output:
999.55
999.56
%5.3f here is two part. one is integer '5' part and another is floating part '.3'. integer part print the number of space before printing the number. And floating part specify how many number will print after floating point. And there are given so many example previous answer.

"rounding" a negative exponential in python

I am looking to convert some small numbers to a simple, readable output. Here is my method but I wondering if there is something simpler.
x = 8.54768039530728989343156856E-58
y = str(x)
print "{0}.e{1}".format(y.split(".")[0], y.split("e")[1])
8.e-58
This gets you pretty close, do you need 8.e-58 exactly or are you just trying to shorten it into something readable?
>>> x = 8.54768039530728989343156856E-58
>>> print "{0:.1e}".format(x)
8.5e-58
An alternative:
>>> print "{0:.0e}".format(x)
9e-58
Note that on Python 2.7 or 3.1+, you can omit the first zero which indicates the position, so it would be something like "{:.1e}".format(x)
like this?
>>> x = 8.54768039530728989343156856E-58
>>> "{:.1e}".format(x)
'8.5e-58'
Another way of doing it, if you ever want to extract the exponent without doing string manipulations.
def frexp_10(decimal):
logdecimal = math.log10(decimal)
return 10 ** (logdecimal - int(logdecimal)), int(logdecimal)
>>> frexp_10(x)
(0.85476803953073244, -57)
Format as you wish...
There are two answers: one for using the number and one for simple display.
For actual numbers:
>>> round(3.1415,2)
3.14
>>> round(1.2345678e-10, 12)
1.23e-10
The built-in round() function will round a number to an arbitrary number of decimal places. You might use this to truncate insignificant digits from readings.
For display, it matters which version of display you use. In Python 2.x, and deprecated in 3.x, you can use the 'e' formatter.
>>> print "%6.2e" % 1.2345678e-10
1.23e-10
or in 3.x, use:
>>> print("{:12.2e}".format(3.1415))
3.14e+00
>>> print("{:12.2e}".format(1.23456789e-10))
1.23e-10
or, if you like the zeros:
>>> print("{:18.14f}".format(1.23456789e-10))
0.00000000012346

Categories

Resources