Using String Format to show decimal up to 2 places or simple integer

Sorry for reactivating this question, but I didn’t find the right answer here. In formatting numbers you can use 0 as a mandatory place and # as an optional place. So: // just two decimal places String.Format(“{0:0.##}”, 123.4567); // “123.46” String.Format(“{0:0.##}”, 123.4); // “123.4” String.Format(“{0:0.##}”, 123.0); // “123” You can also combine 0 with #. … Read more

Display a decimal in scientific notation

from decimal import Decimal ‘%.2E’ % Decimal(‘40800000000.00000000000000’) # returns ‘4.08E+10′ In your ‘40800000000.00000000000000’ there are many more significant zeros that have the same meaning as any other digit. That’s why you have to tell explicitly where you want to stop. If you want to remove all trailing zeros automatically, you can try: def format_e(n): a=”%E” … Read more

How can I format a decimal to always show 2 decimal places?

You should use the new format specifications to define how your value should be represented: >>> from math import pi # pi ~ 3.141592653589793 >>> ‘{0:.2f}’.format(pi) ‘3.14’ The documentation can be a bit obtuse at times, so I recommend the following, easier readable references: the Python String Format Cookbook: shows examples of the new-style .format() … Read more

How to format strings in Java

Take a look at String.format. Note, however, that it takes format specifiers similar to those of C’s printf family of functions — for example: String.format(“Hello %s, %d”, “world”, 42); Would return “Hello world, 42”. You may find this helpful when learning about the format specifiers. Andy Thomas-Cramer was kind enough to leave this link in … Read more