How to print float to n decimal places including trailing 0s?
For Python versions in 2.6+ and 3.xYou can use the str.format
method. Examples:
>>> print('{0:.16f}'.format(1.6))
1.6000000000000001
>>> print('{0:.15f}'.format(1.6))
1.600000000000000
Note the 1
at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.
You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):
>>> print '%.16f' % 1.6
1.6000000000000001
>>> print '%.15f' % 1.6
1.600000000000000
Format a float to n decimal places and no trailing zeros
Enforce that numeric output has at least two trailing decimal places, including trailing zeros
You can use the builtin format
function. .2
refers to the number of digits, and f
refers to "float".
if isPalindrome(candidrome):
print("It's a Palindrome! " + format(candidrome, '.2f'))
Or:
if isPalindrome(candidrome):
print("It's a Palindrome! %.2f" % candidrome)
Add zeros to a float after the decimal point in Python
Format it to 6 decimal places:
format(value, '.6f')
Demo:
>>> format(2.0, '.6f')
'2.000000'
The format()
function turns values to strings following the formatting instructions given.
Is there a way to automatically printf a float to the number of decimal places it has?
Is there a way to automatically printf a float to the number of decimal places it has?
Use "%g"
. "%g"
lops off trailing zero digits.
... unless the # flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining. C17dr § 7.21.6.1 8.
All finite floating point values are exactly representable in decimal - some need many digits to print exactly. Up to DBL_DECIMAL_DIG
from <float.h>
(typically 17) significant digits is sufficient - rarely a need for more.
Pass in a precision to encourage enough output, but not too much.
Remember values like 0.00008
are not exactly encoded in the typical binary floating point double
, but a nearby value is used like 8.00000000000000065442...e-05
printf("%.*g\n", DBL_DECIMAL_DIG, some_double);
printf("%.17g, %.17g, %.17g, %.17g\n", 1.27, 345.1415926535, 1.22013, 0.00008);
// 1.27, 345.14159265350003, 1.2201299999999999, 8.0000000000000007e-05
DBL_DIG
(e.g. 15) may better meet OP's goal.
printf("%.15g, %.15g, %.15g, %.15g\n", 1.27, 345.1415926535, 1.22013, 0.00008);
// 1.27, 345.1415926535, 1.22013, 8e-05
Function to print a double
- exactly may take 100s of digits.
Rounding a number in Python but keeping ending zeros
As you are talking about trailing zeros, this is a question about representation as string,
you can use
>>> "%.2f" % round(2606.89579999999, 2)
'2606.90'
Or use modern style with format
function:
>>> '{:.2f}'.format(round(2606.89579999999, 2))
'2606.90'
and remove point with replace
or translate
(_
refers to result of previous command in python console):
>>> _.translate(None, '.')
'260690'
Note that rounding is not needed here, as .2f
format applyies the same rounding:
>>> "%.2f" % 2606.89579999999
'2606.90'
But as you mentioned excel, you probably would opt to roll your own rounding function, or use decimal, as float.round
can lead to strange results due to float representation:
>>> round(2.675, 2)
2.67
>>> round(2606.89579999999, 2)
2606.89
With decimal use quantize:
>>> from decimal import *
>>> x = Decimal('2606.8950000000001')
# Decimal('2606.8950000000001')
>>> '{}'.format(x.quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))
'2606.90'
That, for your original task, becomes:
>>> x = Decimal('2606.8950000000001')
>>> int((x*100).quantize(1, rounding=ROUND_HALF_EVEN))
260690
And the reason of strange rounding comes to the front with Decimal
:
>>> x = Decimal(2606.8950000000001)
# Decimal('2606.89499999999998181010596454143524169921875') # internal float repr
Convert float to Decimal with fixed digits after decimal
Do all the formatting on the way out from your code, inside the print
and write
statements. There is no reason I can think of to lose precision (and convert the numbers to some fixed format) while doing numeric calculations inside the code.
float number leading and trailing zeros format
use std stream formatters from iomanip.
Stop using printf : Why not use printf() in C++
#include <iostream>
#include <iomanip>
#include <vector>
int main()
{
std::vector<double> values{ 0.001, 0.002, 0.2, 1.001, 9.090, 99.100 };
for (const auto value : values)
{
std::cout << std::fixed;
std::cout << std::setprecision(3);
std::cout << std::setfill('0') << std::setw(7);
std::cout << value << std::endl;
}
return 0;
}
Related Topics
Saving the Output of a Python Program
How to Remove All Characters Before a Specific Character in Python
Export Pandas Dataframe into a Pdf File Using Python
How to Run External Executable Using Python
Pyspark - Sum a Column in Dataframe and Return Results as Int
Pandas: Subtracting Two Date Columns and the Result Being an Integer
Parentheses and Quotation Marks in Output
How to Check Whether a Number Is Divisible by Another Number
How to Delete Tkinter Widgets from a Window
How to Install Pip for a Specific Python Version
How to Increase Dpi With Opencv
How to Find Rows of One Dataframe in Another Dataframe
Pip Error: Microsoft Visual C++ 14.0 Is Required
Cmake on Linux Centos 7, How to Force the System to Use Cmake3
Efficient Way to Unnest (Explode) Multiple List Columns in a Pandas Dataframe