<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python Archives - SignificantFiguresCalculator</title>
	<atom:link href="https://significantfigurescalculator.com/category/tools-code/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://significantfigurescalculator.com/category/tools-code/python/</link>
	<description>Every digit, justified.</description>
	<lastBuildDate>Fri, 20 Nov 2026 11:28:14 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://significantfigurescalculator.com/wp-content/uploads/2026/08/cropped-dd6d33a5-a65a-4d8d-b33e-8b6f5639fddd-150x150.png</url>
	<title>Python Archives - SignificantFiguresCalculator</title>
	<link>https://significantfigurescalculator.com/category/tools-code/python/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Round to Significant Figures in Python Without Floating-Point Surprises</title>
		<link>https://significantfigurescalculator.com/tools-code/python/round-significant-figures-python-without-floating-point-surprises/</link>
					<comments>https://significantfigurescalculator.com/tools-code/python/round-significant-figures-python-without-floating-point-surprises/#respond</comments>
		
		<dc:creator><![CDATA[Tommy C. Moran]]></dc:creator>
		<pubDate>Fri, 20 Nov 2026 11:28:14 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[floating-point]]></category>
		<category><![CDATA[rounding]]></category>
		<category><![CDATA[significant figures]]></category>
		<guid isPermaLink="false">https://significantfigurescalculator.com/?p=391</guid>

					<description><![CDATA[<p>Use Decimal(str(x)), choose an explicit rounding convention, and compute the significant-figure exponent instead of trusting binary floats or Python's built-in round().</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/round-significant-figures-python-without-floating-point-surprises/">How to Round to Significant Figures in Python Without Floating-Point Surprises</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Quick answer:</strong> To round to significant figures in Python without floating-point surprises, convert the value to <code>decimal.Decimal</code> from a string, set a sufficient context precision, compute the target exponent from <code>Decimal.adjusted()</code>, and use <code>quantize()</code> with the rounding mode your standard or instructor requires. Do not rely on <code>round()</code> as a significant-figures formatter. Python&#8217;s <code>round()</code> is a decimal-place or tens-place tool with round-half-even tie-breaking, and binary floats cannot represent most base-10 fractions exactly.</p>
<h2 id="rule-statement">Rule Statement</h2>
<p>Significant figures are the digits in a measured value that carry meaningful information about its precision. Rounding to <em>n</em> significant figures means keeping the first <em>n</em> meaningful digits and replacing the rest with zeros or dropping them, while preserving the magnitude of the value. For a nonzero value <em>x</em>, the target power of ten is <strong><em>e</em> = floor(log<sub>10</sub>(|x|)) − n + 1</strong>. The rounded value is the nearest multiple of 10<sup><em>e</em></sup>, using the tie rule you have chosen.</p>
<blockquote><p>Python is not the standard; it is a tool. Choose the rounding convention required by your lab, standard, or instructor, then encode it explicitly in code.</p></blockquote>
<p>The general digit rule is familiar: if the first dropped digit is greater than 5, round up; if it is less than 5, round down. If it is exactly 5 followed by nonzero digits, round up. If it is exactly 5 with nothing but zeros after it, the convention matters: half-up, half-even, half-down, and truncation all give different answers. See our <a href="/rounding-rules/">rounding rules</a> and <a href="/why-sig-figs-are-an-approximation/">Why Sig Figs Are an Approximation</a> for deeper background.</p>
<h2 id="software-behavior-note-python-floats-round-decimal-and-fraction">Software Behavior Note: Python Floats, <code>round()</code>, <code>Decimal</code>, and <code>Fraction</code></h2>
<p>Python&#8217;s <code>float</code> is IEEE 754 binary64. Most decimal fractions, including 0.1, 2.675, and 0.0012345, have no exact binary representation. That is why <code>0.1 + 0.2</code> is not exactly <code>0.3</code>, and why <code>round(2.675, 2)</code> returns <code>2.67</code> rather than <code>2.68</code>. The stored float is slightly less than 2.675, so the tie never occurs.</p>
<p>Python&#8217;s built-in <code>round()</code> has two additional surprises for metrology work:</p>
<ul>
<li><strong>Tie rule:</strong> for exact binary ties, <code>round()</code> uses round-half-even, often called banker&#8217;s rounding. This is useful in finance and some standards, but it is not always the classroom or laboratory convention.</li>
<li><strong>Not significant figures:</strong> <code>round(x, n)</code> rounds to <em>n</em> decimal places, not <em>n</em> significant figures. <code>round(12345, -2)</code> rounds to hundreds, not to three significant figures in a general way.</li>
</ul>
<p>For decimal-safe work, use <code>Decimal</code> constructed from a string. The expression <code>Decimal(str(x))</code> preserves the decimal value the user intended, whereas <code>Decimal(x)</code> converts the already-corrupted binary float. A robust significant-figures function looks like this:</p>
<pre><code>from decimal import Decimal, localcontext, ROUND_HALF_UP

def round_sig(x, sig=3, rounding=ROUND_HALF_UP):
    d = Decimal(str(x))
    if d.is_zero():
        return Decimal('0')
    with localcontext() as ctx:
        ctx.prec = max(28, len(d.as_tuple().digits) + sig + 5)
        exponent = d.adjusted() - sig + 1
        rounded = d.quantize(Decimal(1).scaleb(exponent), rounding=rounding)
        # handle carry such as 999.9 -&gt; 1000
        exponent2 = rounded.adjusted() - sig + 1
        if exponent2 != exponent:
            rounded = d.quantize(Decimal(1).scaleb(exponent2), rounding=rounding)
        return rounded</code></pre>
<p>For exact rational arithmetic, <code>fractions.Fraction</code> can avoid decimal representation issues, but it does not by itself define significant-figure output or trailing-zero display. In practice, <code>Decimal</code> is usually the right tool for measurement-style significant-figure rounding.</p>
<h2 id="worked-examples">Worked Examples</h2>
<h3 id="1-12345-to-3-significant-figures">1. 12,345 to 3 significant figures</h3>
<p><code>Decimal('12345').adjusted()</code> is 4. The target exponent is 4 − 3 + 1 = 2. Quantize to <code>1E+2</code>, giving <code>Decimal('1.23E+4')</code>. Displayed as 1.23 × 10<sup>4</sup> or 12,300 with a note that the trailing zeros are placeholders unless the measurement resolution supports them.</p>
<h3 id="2-0-0012345-to-3-significant-figures">2. 0.0012345 to 3 significant figures</h3>
<p>The adjusted exponent is −3. The target exponent is −3 − 3 + 1 = −5. Quantize to <code>1E-5</code>, giving 0.00123.</p>
<h3 id="3-2-675-to-3-significant-figures">3. 2.675 to 3 significant figures</h3>
<p>Using <code>Decimal('2.675')</code> with <code>ROUND_HALF_UP</code> gives 2.68. Using binary <code>round(2.675, 2)</code> gives 2.67 because the float is stored as approximately 2.674999999999999822. This is the classic floating-point surprise.</p>
<h3 id="4-2-685-to-3-significant-figures">4. 2.685 to 3 significant figures</h3>
<p>Half-up gives 2.69. Half-even gives 2.68 because the retained digit 8 is even. This example shows why conventions must be declared. A calculator or programming language that does not expose its tie rule can silently disagree with a specification.</p>
<h3 id="5-999-9-to-3-significant-figures">5. 999.9 to 3 significant figures</h3>
<p>The initial target exponent is 0, and rounding gives 1000. The magnitude has carried, so re-quantize to <code>1E+1</code> to preserve three significant digits: <code>Decimal('1.00E+3')</code>. Without carry handling, the result may appear to have only one significant figure.</p>
<h2 id="counter-examples">Counter-Examples</h2>
<ul>
<li><strong><code>round(2.675, 2)</code> → 2.67:</strong> This is not a significant-figure rule; it is binary representation plus round-half-even.</li>
<li><strong><code>Decimal(2.675)</code>:</strong> This converts the binary float, producing <code>Decimal('2.67499999999999982236431605997495353221893310546875')</code>. Use <code>Decimal(str(2.675))</code> instead.</li>
<li><strong><code>round(12345, -3)</code>:</strong> This rounds to thousands, not to a general number of significant figures. It fails as soon as the magnitude changes.</li>
<li><strong><code>round(1.20, 1)</code> → 1.2:</strong> This loses the trailing zero that may carry significant-figure meaning. Preserve display precision separately from numeric value.</li>
<li><strong>Double rounding:</strong> Rounding 2.4445 to 2 significant figures by first rounding to 2.445 then to 2.4 can produce a different result than rounding directly. See <a href="/double-rounding-error/">Double Rounding Error</a>.</li>
</ul>
<h2 id="convention-comparison-table">Convention Comparison Table</h2>
<table>
<thead>
<tr>
<th>Convention</th>
<th>Exact tie behavior</th>
<th>Typical use</th>
<th>Python Decimal mode</th>
</tr>
</thead>
<tbody>
<tr>
<td>Half-up</td>
<td>Always round away from zero on exact 5</td>
<td>School arithmetic, many lab reports</td>
<td><code>ROUND_HALF_UP</code></td>
</tr>
<tr>
<td>Half-even</td>
<td>Round to nearest even retained digit</td>
<td>ASTM E29, ISO 80000, finance, floating-point hardware</td>
<td><code>ROUND_HALF_EVEN</code></td>
</tr>
<tr>
<td>Half-down</td>
<td>Always round toward zero on exact 5</td>
<td>Specialized conservative estimates</td>
<td><code>ROUND_HALF_DOWN</code></td>
</tr>
<tr>
<td>Ceiling</td>
<td>Always round up</td>
<td>Tolerance limits, safety margins</td>
<td><code>ROUND_CEILING</code></td>
</tr>
<tr>
<td>Floor</td>
<td>Always round down</td>
<td>Lower bounds, truncation-like limits</td>
<td><code>ROUND_FLOOR</code></td>
</tr>
<tr>
<td>Truncation</td>
<td>Discard extra digits</td>
<td>Some digital instruments and intermediate displays</td>
<td><code>ROUND_DOWN</code></td>
</tr>
</tbody>
</table>
<h2 id="standards-citation">Standards Citation</h2>
<p>Significant-figure rounding is not a single universal algorithm. Standards define acceptable practice for specific domains:</p>
<ul>
<li><strong>ASTM E29-22</strong>, <em>Standard Practice for Using Significant Digits in Test Data to Determine Conformance with Specifications</em>, Sections 6–7, covers rounding and significant-digit use in test data. It is widely cited when deciding whether a measured value conforms to a specification.</li>
<li><strong>ISO 80000-1:2022</strong>, <em>Quantities and units — Part 1: General</em>, Clause 7.3, gives rounding conventions, including the treatment of exact ties. The half-even convention is common in metrology and standardization.</li>
<li><strong>JCGM 100:2008</strong>, the <em>Guide to the expression of uncertainty in measurement</em> (GUM), Clause 7.2.6, advises against excessive digits when reporting estimates and uncertainties. Many fields report uncertainty to one or two significant digits.</li>
<li><strong>NIST SP 811</strong>, <em>Guide for the Use of the International System of Units (SI)</em>, Section 7.4, discusses rounding values and the importance of matching the reported digits to the measurement uncertainty.</li>
</ul>
<blockquote><p>Always record the rounding convention with the data. A number rounded half-up can differ from the same number rounded half-even by one unit in the last retained place.</p></blockquote>
<h2 id="common-mistakes">Common Mistakes</h2>
<ul>
<li><strong>Using <code>round()</code> for significant figures.</strong> It rounds to decimal places, not significant digits, and its tie rule is not configurable.</li>
<li><strong>Using <code>Decimal(float)</code>.</strong> This preserves the binary error instead of the intended decimal value. Use <code>Decimal(str(x))</code> or <code>Decimal('2.675')</code>.</li>
<li><strong>Forgetting context precision.</strong> Decimal operations are affected by the current context. Increase precision locally before quantizing.</li>
<li><strong>Assuming trailing zeros are significant.</strong> 1200 may have two, three, or four significant figures. See <a href="/ambiguous-trailing-zeros/">Ambiguous Trailing Zeros</a>.</li>
<li><strong>Mixing conventions silently.</strong> Half-up and half-even are both defensible, but only one may match your specification.</li>
<li><strong>Rounding intermediate results.</strong> Keep full precision through calculations and round only the final reported value, unless a standard says otherwise.</li>
<li><strong>Ignoring zero.</strong> Zero has no nonzero significant digits; its precision must be defined by context, uncertainty, or measurement resolution.</li>
</ul>
<h2 id="quick-reference-table">Quick Reference Table</h2>
<table>
<thead>
<tr>
<th>Task</th>
<th>Recommended Python</th>
<th>Note</th>
</tr>
</thead>
<tbody>
<tr>
<td>Create exact decimal</td>
<td><code>Decimal(str(x))</code></td>
<td>Do not use <code>Decimal(float)</code> for intended decimal ties.</td>
</tr>
<tr>
<td>Round to n sig figs</td>
<td><code>round_sig(x, n, ROUND_HALF_UP)</code></td>
<td>Compute exponent with <code>adjusted()</code>; handle carry.</td>
</tr>
<tr>
<td>Use half-even</td>
<td><code>rounding=ROUND_HALF_EVEN</code></td>
<td>Common in ASTM, ISO, and IEEE 754.</td>
</tr>
<tr>
<td>Use half-up</td>
<td><code>rounding=ROUND_HALF_UP</code></td>
<td>Common in education and general reporting.</td>
</tr>
<tr>
<td>Preserve trailing zeros</td>
<td><code>quantize(Decimal('1E-3'))</code></td>
<td>Numeric value and displayed precision are separate concerns.</td>
</tr>
<tr>
<td>Exact rational work</td>
<td><code>Fraction('2.675')</code></td>
<td>Useful for exact arithmetic, but define your rounding rule separately.</td>
</tr>
</tbody>
</table>
<h2 id="sources-further-reading">Sources &amp; Further Reading</h2>
<ul>
<li>ASTM E29-22, <em>Standard Practice for Using Significant Digits in Test Data to Determine Conformance with Specifications</em>, ASTM International.</li>
<li>ISO 80000-1:2022, <em>Quantities and units — Part 1: General</em>, Clause 7.3.</li>
<li>JCGM 100:2008, <em>Evaluation of measurement data — Guide to the expression of uncertainty in measurement</em> (GUM), Clause 7.2.6.</li>
<li>NIST Special Publication 811, <em>Guide for the Use of the International System of Units (SI)</em>, Section 7.4.</li>
<li>Python Software Foundation, <em>decimal — Decimal fixed point and floating point arithmetic</em>.</li>
</ul>
<p>This site is a precision and rounding reference, not just a calculator. The calculator is designed to apply these rules accurately, but the surrounding reference material explains why the rules exist, how standards differ, and where floating-point implementations can mislead. For related topics, see <a href="/rounding-methods/">Rounding Methods</a>, <a href="/bankers-rounding/">Banker&#8217;s Rounding</a>, and <a href="/python/">Python</a>.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/round-significant-figures-python-without-floating-point-surprises/">How to Round to Significant Figures in Python Without Floating-Point Surprises</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://significantfigurescalculator.com/tools-code/python/round-significant-figures-python-without-floating-point-surprises/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Sig Figs in Python: round(), format(), and Decimal — Which One Follows ASTM E29?</title>
		<link>https://significantfigurescalculator.com/tools-code/python/python-sig-figs-round-format-decimal-astm-e29/</link>
					<comments>https://significantfigurescalculator.com/tools-code/python/python-sig-figs-round-format-decimal-astm-e29/#respond</comments>
		
		<dc:creator><![CDATA[Tommy C. Moran]]></dc:creator>
		<pubDate>Sun, 25 Oct 2026 09:22:29 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[ASTM E29]]></category>
		<category><![CDATA[rounding]]></category>
		<category><![CDATA[significant figures]]></category>
		<guid isPermaLink="false">https://significantfigurescalculator.com/?p=307</guid>

					<description><![CDATA[<p>Python's round() and format() use half-even ties, matching ASTM E29 for exact ties, but binary floats can break decimal rounding. Decimal.quantize() is the reliable ASTM-compliant choice.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/python-sig-figs-round-format-decimal-astm-e29/">Sig Figs in Python: round(), format(), and Decimal — Which One Follows ASTM E29?</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Python is a first-class tool for scientific computing, but its default numeric types can surprise anyone who needs standards-compliant significant figures. The question is not merely which function rounds, but which one follows <strong>ASTM E29</strong>, the standard practice for using significant digits in test data. The short answer: Python&#8217;s <code>round()</code>, <code>format()</code>, and <code>Decimal</code> all use <em>round-half-to-even</em> for exact ties, which aligns with ASTM E29. However, binary floating-point representation means <code>round()</code> and <code>format()</code> on floats can fail decimal ties. For ASTM-compliant decimal rounding, use <code>Decimal.quantize()</code> with an explicit rounding mode.</p>
<h2 id="rule-statement-what-astm-e29-actually-requires">Rule Statement: What ASTM E29 Actually Requires</h2>
<p>ASTM E29-13, <em>Standard Practice for Using Significant Digits in Test Data to Determine Conformance with Specifications</em>, specifies a rounding method in Section 6.1. When the digit immediately beyond the last place to be retained is less than 5, retain unchanged. When it is greater than 5, increase by one. When it is exactly 5, round to the nearest even digit. This is the <a href="/bankers-rounding">banker&#8217;s rounding</a> rule, also called round-half-even.</p>
<blockquote><p>ASTM E29 Section 6.1: If the digit next beyond the last place to be retained is exactly 5, round to the nearest even digit.</p></blockquote>
<p>Python&#8217;s <code>round()</code> for floats and <code>Decimal</code> in its default context both use round-half-even. The <code>format()</code> function for floats also resolves exact ties to even. The catch is that most decimal fractions are not exact in binary, so a value like 2.675 is stored as something slightly less than 2.675. That makes <code>round(2.675, 2)</code> return 2.67, not 2.68. <code>Decimal</code> constructed from a string avoids this trap.</p>
<h2 id="standards-citation">Standards Citation</h2>
<ul>
<li><strong>ASTM E29-13</strong>, Section 6.1 — Rounding off to significant digits; ties to even.</li>
<li><strong>ISO 80000-1:2009</strong>, <em>Quantities and units — Part 1: General</em>, Clause 6.4.3 — Recommends rounding to nearest, ties to even.</li>
<li><strong>NIST SP 811</strong>, <em>Guide for the Use of the International System of Units (SI)</em>, Section 7.4 — Discusses rounding and significant figures.</li>
<li><strong>JCGM 100:2008 (GUM)</strong>, Clause 7.2.6 — Reporting uncertainty and rounding measurement results.</li>
<li><strong>Python 3 Documentation</strong> — <code>decimal</code>, <code>round()</code>, and format specification mini-language.</li>
</ul>
<h2 id="software-behavior-note-round-format-and-decimal">Software Behavior Note: round(), format(), and Decimal</h2>
<h3 id="round">round()</h3>
<p><code>round(number, ndigits)</code> returns a numeric value. For exact ties, Python 3 uses round-half-even. For example, <code>round(2.5)</code> returns <code>2</code> and <code>round(3.5)</code> returns <code>4</code>. But <code>round()</code> on a binary float is limited by the float&#8217;s actual stored value. It rounds to decimal places, not significant figures.</p>
<h3 id="format">format()</h3>
<p><code>format(value, '.2f')</code> returns a string for display. It uses correctly rounded decimal conversion and resolves exact ties to even. For example, <code>format(2.5, '.0f')</code> returns <code>'2'</code>. The <code>'.3g'</code> format rounds to three significant figures, but may switch to scientific notation. <code>format()</code> does not change the original value.</p>
<h3 id="decimal">Decimal</h3>
<p><code>Decimal</code> provides exact decimal arithmetic. Its default context uses <code>ROUND_HALF_EVEN</code>, matching ASTM E29. The most explicit method is <code>Decimal('2.5').quantize(Decimal('1'), rounding=ROUND_HALF_EVEN)</code>, which returns <code>Decimal('2')</code>. For significant figures, compute the correct exponent and quantize.</p>
<h2 id="convention-comparison-table">Convention Comparison Table</h2>
<table>
<thead>
<tr>
<th>Convention</th>
<th>Rule for exact tie</th>
<th>ASTM E29 alignment</th>
<th>Python implementation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Round half up</td>
<td>Always round away from zero</td>
<td>No</td>
<td>Not default in Python</td>
</tr>
<tr>
<td>Round half even</td>
<td>Round to nearest even digit</td>
<td>Yes</td>
<td><code>round()</code>, <code>format()</code>, <code>Decimal</code> default</td>
</tr>
<tr>
<td>Round half down</td>
<td>Always round toward zero</td>
<td>No</td>
<td>Available in <code>Decimal</code> as <code>ROUND_HALF_DOWN</code></td>
</tr>
<tr>
<td>Truncation</td>
<td>Drop extra digits</td>
<td>No</td>
<td><code>math.trunc()</code>, <code>Decimal</code> quantize with <code>ROUND_DOWN</code></td>
</tr>
</tbody>
</table>
<h2 id="worked-examples">Worked Examples</h2>
<h3 id="example-1-decimal-tie-2-5">Example 1: Decimal tie 2.5</h3>
<p>Round 2.5 to an integer under ASTM E29. The digit to drop is 5, so round to the nearest even digit. The preceding digit is 2, which is even, so retain 2. Python: <code>round(2.5)</code> → <code>2</code>. <code>Decimal('2.5').quantize(Decimal('1'), rounding=ROUND_HALF_EVEN)</code> → <code>Decimal('2')</code>. This matches ASTM E29.</p>
<h3 id="example-2-binary-float-trap-2-675">Example 2: Binary float trap 2.675</h3>
<p>Round 2.675 to two decimal places. ASTM E29 would examine the third decimal, a 5, and round to even: 2.68. But <code>round(2.675, 2)</code> returns <code>2.67</code> because the binary float is slightly less than 2.675. <code>Decimal('2.675').quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN)</code> returns <code>Decimal('2.68')</code>. Use <code>Decimal</code> when decimal exactness matters.</p>
<h3 id="example-3-significant-figures-12345-to-3-sig-figs">Example 3: Significant figures 12345 to 3 sig figs</h3>
<p>To round 12345 to three significant figures, the retained digits are 1, 2, and 3. The next digit is 4, so the result is 12300. Python&#8217;s <code>round(12345, -2)</code> returns 12300, but this only works because the decimal-place offset happens to match. A general function uses <code>Decimal</code>:</p>
<pre><code>from decimal import Decimal, ROUND_HALF_EVEN

def round_sig(x, sig):
    d = Decimal(str(x))
    if d.is_zero():
        return d
    exponent = d.adjusted() - sig + 1
    return d.quantize(Decimal('1E{}'.format(exponent)), rounding=ROUND_HALF_EVEN)

round_sig(12345, 3)  # Decimal('1.23E+4')
round_sig(0.012345, 3)  # Decimal('0.0123')</code></pre>
<p>This approach follows ASTM E29 for decimal data and avoids binary float artifacts.</p>
<h2 id="counter-examples">Counter-Examples</h2>
<ul>
<li><strong>Assuming half-up:</strong> <code>round(2.5)</code> gives 2, not 3. If your process requires half-up, Python&#8217;s default is wrong for you.</li>
<li><strong>Using round() for sig figs:</strong> <code>round(12345, 3)</code> rounds to three decimal places, returning 12345. It does not round to three significant figures.</li>
<li><strong>Double rounding:</strong> <code>round(1.2349, 2)</code> gives 1.23. If you first round to three decimals, <code>round(1.2349, 3)</code> gives 1.235, then <code>round(1.235, 2)</code> gives 1.24. The intermediate rounding changed the final result.</li>
<li><strong>Formatting as rounding:</strong> <code>format(2.5, '.0f')</code> returns <code>'2'</code>, but the variable still holds 2.5. Formatting is display, not mutation.</li>
</ul>
<h2 id="common-mistakes">Common Mistakes</h2>
<ul>
<li>Confusing decimal places with <a href="/significant-figures">significant figures</a>.</li>
<li>Using binary floats for decimal rounding and expecting exact ties.</li>
<li>Rounding intermediate values before the final calculation.</li>
<li>Assuming Python&#8217;s <code>round()</code> is half-up because that is taught in some schools.</li>
<li>Ignoring ASTM E29&#8217;s tie-to-even rule when checking conformance to specifications.</li>
<li>Not using <code>Decimal</code> when input values are decimal strings from instruments or databases.</li>
</ul>
<h2 id="quick-reference-table">Quick Reference Table</h2>
<table>
<thead>
<tr>
<th>Task</th>
<th>Recommended Python</th>
<th>ASTM E29 alignment</th>
</tr>
</thead>
<tbody>
<tr>
<td>Round exact decimal to decimal places</td>
<td><code>Decimal.quantize(..., ROUND_HALF_EVEN)</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Round float to decimal places</td>
<td><code>round()</code> or <code>format()</code></td>
<td>Usually, but binary caveat</td>
</tr>
<tr>
<td>Round to significant figures</td>
<td><code>Decimal</code> with computed exponent</td>
<td>Yes</td>
</tr>
<tr>
<td>Format for display</td>
<td><code>format()</code> or f-string</td>
<td>Yes for ties, display only</td>
</tr>
<tr>
<td>Round to nearest integer</td>
<td><code>round()</code></td>
<td>Yes for ties to even</td>
</tr>
</tbody>
</table>
<h2 id="sources-further-reading">Sources &amp; Further Reading</h2>
<ul>
<li>ASTM E29-13, <em>Standard Practice for Using Significant Digits in Test Data to Determine Conformance with Specifications</em>, ASTM International.</li>
<li>ISO 80000-1:2009, <em>Quantities and units — Part 1: General</em>, Clause 6.4.3.</li>
<li>NIST Special Publication 811, <em>Guide for the Use of the International System of Units (SI)</em>, Section 7.4.</li>
<li>JCGM 100:2008, <em>Evaluation of measurement data — Guide to the expression of uncertainty in measurement (GUM)</em>, Clause 7.2.6.</li>
<li>Python Software Foundation, <em>Python 3 Documentation: decimal — Decimal fixed point and floating point arithmetic</em>.</li>
</ul>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/python-sig-figs-round-format-decimal-astm-e29/">Sig Figs in Python: round(), format(), and Decimal — Which One Follows ASTM E29?</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://significantfigurescalculator.com/tools-code/python/python-sig-figs-round-format-decimal-astm-e29/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Round to Significant Figures in Python Using the decimal Module</title>
		<link>https://significantfigurescalculator.com/tools-code/python/python-decimal-significant-figures/</link>
					<comments>https://significantfigurescalculator.com/tools-code/python/python-decimal-significant-figures/#respond</comments>
		
		<dc:creator><![CDATA[Tommy C. Moran]]></dc:creator>
		<pubDate>Fri, 23 Oct 2026 17:47:54 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[ASTM E29]]></category>
		<category><![CDATA[rounding]]></category>
		<category><![CDATA[significant figures]]></category>
		<guid isPermaLink="false">https://significantfigurescalculator.com/?p=315</guid>

					<description><![CDATA[<p>Use Decimal.quantize with an exponent derived from the adjusted exponent to round to n significant figures, choosing ROUND_HALF_EVEN for standards-aligned ties.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/python-decimal-significant-figures/">How to Round to Significant Figures in Python Using the decimal Module</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>This reference explains how to round to significant figures in Python using the <strong>decimal</strong> module. It is part of a precision-and-rounding reference site, not merely a calculator. The goal is to give students, engineers, scientists, and educators a reliable, standards-aware guide to <a href="/significant-figures">significant figures</a>, <a href="/rounding-rules">rounding rules</a>, and the exact behavior of Python&#8217;s <code>decimal</code> type.</p>
<h2 id="rule-statement">Rule Statement</h2>
<p>Rounding to <em>n</em> significant figures means keeping the first <em>n</em> meaningful digits, starting from the first nonzero digit, and replacing the rest with zeros or dropping them. In Python, the <code>decimal</code> module does not provide a direct <code>round_sig()</code> function. Instead, use <code>Decimal.quantize()</code> with an exponent that corresponds to the desired place value.</p>
<p>For a nonzero <code>Decimal</code> <code>x</code>, the target exponent is:</p>
<blockquote><p><strong>exponent = x.adjusted() &#8211; n + 1</strong></p></blockquote>
<p>Here <code>adjusted()</code> returns the exponent of the most significant digit. For example, <code>Decimal('1234.567').adjusted()</code> is <code>3</code>, and <code>Decimal('0.0012345').adjusted()</code> is <code>-3</code>. Then <code>quantize(Decimal('1e{exponent}'))</code> rounds to that place value.</p>
<pre><code>from decimal import Decimal, localcontext, ROUND_HALF_EVEN

def round_sig(x, n, rounding=ROUND_HALF_EVEN):
    x = Decimal(x) if not isinstance(x, Decimal) else x
    if x.is_zero():
        return x
    exp = x.adjusted() - n + 1
    q = Decimal('1e{}'.format(exp))
    with localcontext() as ctx:
        ctx.prec = max(28, len(x.as_tuple().digits) + abs(exp) + 5)
        return x.quantize(q, rounding=rounding)
</code></pre>
<p>Always construct <code>Decimal</code> values from strings, such as <code>Decimal('2.675')</code>, not from binary floats. This avoids hidden binary artifacts that corrupt rounding.</p>
<h2 id="software-behavior-note">Software Behavior Note</h2>
<p>The Python <code>decimal</code> module implements the IBM General Decimal Arithmetic Specification. Its default context rounding mode is <code>ROUND_HALF_EVEN</code>, also called banker&#8217;s rounding. This aligns with several metrology and standards conventions for tie-breaking.</p>
<p><code>quantize()</code> rounds to a fixed exponent, not directly to significant figures. It also respects the current context precision. If the result would have more digits than the context allows, <code>quantize()</code> may raise <code>InvalidOperation</code>. Set <code>ctx.prec</code> high enough for large coefficients, especially when rounding very large or very small numbers.</p>
<p>Zero is special: <code>Decimal('0').adjusted()</code> is <code>0</code>, but the number of significant figures in zero is ambiguous. Standards such as <a href="/ambiguous-trailing-zeros">ambiguous trailing zeros</a> treat zeros as significant only when explicitly indicated. The helper above returns zero unchanged.</p>
<h2 id="worked-examples">Worked Examples</h2>
<h3 id="example-1-1234-567-to-3-significant-figures">Example 1: 1234.567 to 3 significant figures</h3>
<ol>
<li><code>Decimal('1234.567').adjusted()</code> = <code>3</code>.</li>
<li>Target exponent = <code>3 - 3 + 1 = 1</code>.</li>
<li>Quantize to <code>Decimal('1e1')</code>, which is 10.</li>
<li>With <code>ROUND_HALF_UP</code>, 1234.567 becomes 1230.</li>
</ol>
<pre><code>Decimal('1234.567').quantize(Decimal('1e1'), rounding=ROUND_HALF_UP)
# Decimal('1.23E+3')
</code></pre>
<p>Result: <strong>1.23 × 10<sup>3</sup></strong>, or 1230 in positional notation.</p>
<h3 id="example-2-0-0012345-to-3-significant-figures">Example 2: 0.0012345 to 3 significant figures</h3>
<ol>
<li><code>Decimal('0.0012345').adjusted()</code> = <code>-3</code>.</li>
<li>Target exponent = <code>-3 - 3 + 1 = -5</code>.</li>
<li>Quantize to <code>Decimal('1e-5')</code>.</li>
<li>Result: <code>0.00123</code>.</li>
</ol>
<pre><code>Decimal('0.0012345').quantize(Decimal('1e-5'), rounding=ROUND_HALF_UP)
# Decimal('0.00123')
</code></pre>
<h3 id="example-3-2-5-to-1-significant-figure">Example 3: 2.5 to 1 significant figure</h3>
<p>Under <code>ROUND_HALF_EVEN</code>, 2.5 rounds to <strong>2</strong> because the retained digit 2 is even. Under <code>ROUND_HALF_UP</code>, 2.5 rounds to <strong>3</strong>. This is the classic tie-breaking difference between banker&#8217;s rounding and half-up rounding.</p>
<h2 id="counter-examples">Counter-Examples</h2>
<ul>
<li><strong>Float contamination:</strong> <code>Decimal(2.675)</code> is actually <code>2.674999999999999822...</code>. Quantizing to two decimal places with <code>ROUND_HALF_UP</code> gives <code>2.67</code>, not <code>2.68</code>. Use <code>Decimal('2.675')</code>.</li>
<li><strong>Double rounding:</strong> Rounding 1.245 to 2 significant figures directly gives <code>1.2</code>. But rounding first to 3 significant figures gives <code>1.25</code>, then to 2 gives <code>1.3</code>. That is a <a href="/double-rounding-error">double rounding error</a>.</li>
<li><strong>Decimal places vs significant figures:</strong> <code>f'{1234.567:.2f}'</code> gives <code>1234.57</code>, which has two decimal places, not two significant figures. The correct 3-significant-figure result is <code>1230</code>.</li>
<li><strong>Insufficient context precision:</strong> <code>quantize()</code> can fail for very large coefficients if <code>ctx.prec</code> is too low. Always raise precision before quantizing.</li>
</ul>
<h2 id="convention-comparison-table">Convention Comparison Table</h2>
<table>
<tr>
<th>Convention</th>
<th>Tie-breaking</th>
<th>Typical use</th>
<th>Python constant</th>
</tr>
<tr>
<td>Half-even (banker&#8217;s)</td>
<td>Round to nearest even last digit</td>
<td>ASTM E29, ISO 80000, Python default</td>
<td><code>ROUND_HALF_EVEN</code></td>
</tr>
<tr>
<td>Half-up</td>
<td>Always round 5 up</td>
<td>Everyday math, some finance</td>
<td><code>ROUND_HALF_UP</code></td>
</tr>
<tr>
<td>Half-down</td>
<td>Always round 5 down</td>
<td>Specialized fields</td>
<td><code>ROUND_HALF_DOWN</code></td>
</tr>
<tr>
<td>Truncation</td>
<td>Drop extra digits</td>
<td>Conservative limits</td>
<td><code>ROUND_DOWN</code></td>
</tr>
</table>
<h2 id="standards-citation">Standards Citation</h2>
<p><strong>ASTM E29-13a, Section 6.2</strong> recommends rounding ties to the nearest even digit for test data conformance. <strong>ISO 80000-1:2009, Clause 7.3.3</strong> gives the same rule for general quantities and units. <strong>JCGM 100:2008 (GUM), Clause 7.2.6</strong> advises reporting uncertainty to at most two significant digits. <strong>NIST SP 811, Section 7.9</strong> provides rounding guidance for SI values. Python&#8217;s default <code>ROUND_HALF_EVEN</code> is therefore a defensible choice for standards-aligned work.</p>
<blockquote><p>GUM 7.2.6: The numerical values of the estimate and its uncertainty should not be given with an excessive number of digits. In practice, uncertainty is often reported to two significant digits.</p></blockquote>
<h2 id="common-mistakes">Common Mistakes</h2>
<ul>
<li>Using <code>Decimal(float)</code> instead of <code>Decimal('string')</code>.</li>
<li>Confusing decimal places with significant figures.</li>
<li>Forgetting to increase context precision before <code>quantize()</code>.</li>
<li>Using built-in <code>round()</code> for significant figures; it rounds to decimal places and uses binary floats.</li>
<li>Double rounding: rounding twice instead of once to the final precision.</li>
<li>Assuming trailing zeros are never significant; in measurement they can be.</li>
</ul>
<h2 id="quick-reference-table">Quick Reference Table</h2>
<table>
<tr>
<th>Task</th>
<th>Code pattern</th>
</tr>
<tr>
<td>Import tools</td>
<td><code>from decimal import Decimal, localcontext, ROUND_HALF_EVEN</code></td>
</tr>
<tr>
<td>Find target exponent</td>
<td><code>exp = x.adjusted() - n + 1</code></td>
</tr>
<tr>
<td>Build quantizer</td>
<td><code>q = Decimal('1e{}'.format(exp))</code></td>
</tr>
<tr>
<td>Round to n sig figs</td>
<td><code>x.quantize(q, rounding=ROUND_HALF_EVEN)</code></td>
</tr>
<tr>
<td>Use high precision</td>
<td><code>with localcontext() as ctx: ctx.prec = 50</code></td>
</tr>
</table>
<h2 id="related-rules">Related Rules</h2>
<ul>
<li><a href="/rounding-rules">Rounding Rules</a></li>
<li><a href="/significant-figures">Significant Figures</a></li>
<li><a href="/bankers-rounding">Banker&#8217;s Rounding</a></li>
<li><a href="/python-floating-point">Python Floating-Point</a></li>
<li><a href="/gum-guide">GUM Guide</a></li>
</ul>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/python-decimal-significant-figures/">How to Round to Significant Figures in Python Using the decimal Module</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://significantfigurescalculator.com/tools-code/python/python-decimal-significant-figures/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Why Python’s round() Uses Banker’s Rounding: A Precision Reference</title>
		<link>https://significantfigurescalculator.com/tools-code/python/why-pythons-round-uses-bankers-rounding/</link>
					<comments>https://significantfigurescalculator.com/tools-code/python/why-pythons-round-uses-bankers-rounding/#respond</comments>
		
		<dc:creator><![CDATA[Tommy C. Moran]]></dc:creator>
		<pubDate>Sun, 09 Aug 2026 09:41:22 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://significantfigurescalculator.test/uncategorized/why-pythons-round-uses-bankers-rounding/</guid>

					<description><![CDATA[<p>Python's round() implements banker's rounding (round half to even) to reduce cumulative bias in statistical operations. This article explains the rationale, standards, and practical implications.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/why-pythons-round-uses-bankers-rounding/">Why Python’s round() Uses Banker’s Rounding: A Precision Reference</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>When you call <code>round(2.5)</code> in Python, you might expect <code>3</code> based on the common “round half up” rule taught in many classrooms. Instead, Python returns <code>2</code>. This behavior, known as <strong>banker’s rounding</strong> or <strong>round half to even</strong>, is not a quirk but a deliberate design choice rooted in statistical accuracy and international standards. This article, part of our <a href="/precision-reference">precision and rounding reference</a>, explains why Python adopts this convention, how it aligns with metrology standards, and what it means for your calculations.</p>
<h2 id="rule-statement">Rule Statement</h2>
<p>Banker’s rounding is a tie-breaking rule for rounding numbers exactly halfway between two possible rounded values. The rule states: <em>when the fractional part is exactly 0.5, round to the nearest even digit</em>. For example:</p>
<ul>
<li><code>round(2.5)</code> → <code>2</code> (2 is even)</li>
<li><code>round(3.5)</code> → <code>4</code> (4 is even)</li>
<li><code>round(1.25, 1)</code> → <code>1.2</code> (2 is even)</li>
<li><code>round(1.35, 1)</code> → <code>1.4</code> (4 is even)</li>
</ul>
<p>This rule applies to both positive and negative numbers. For negative numbers, the same logic applies to the absolute value: <code>round(-2.5)</code> → <code>-2</code> because 2 is even, and <code>round(-3.5)</code> → <code>-4</code> because 4 is even.</p>
<p>The rationale is to avoid the systematic upward bias introduced by the more common “round half up” rule. In a large dataset with many ties, half-up rounding consistently increases the average, whereas half-even rounding distributes ties evenly between even and odd results, keeping the statistical expectation unbiased.</p>
<h2 id="worked-examples">Worked Examples</h2>
<p>Let’s walk through several examples to see how banker’s rounding works in practice, including cases with a specified number of decimal places.</p>
<h3 id="example-1-rounding-to-the-nearest-integer">Example 1: Rounding to the Nearest Integer</h3>
<ol>
<li><code>round(2.5)</code> – The fractional part is exactly 0.5. The two nearest integers are 2 and 3. Since 2 is even, the result is <strong>2</strong>.</li>
<li><code>round(3.5)</code> – The two nearest integers are 3 and 4. Since 4 is even, the result is <strong>4</strong>.</li>
<li><code>round(4.5)</code> – The two nearest integers are 4 and 5. Since 4 is even, the result is <strong>4</strong>.</li>
<li><code>round(5.5)</code> – The two nearest integers are 5 and 6. Since 6 is even, the result is <strong>6</strong>.</li>
</ol>
<h3 id="example-2-rounding-to-a-specified-number-of-decimal-places">Example 2: Rounding to a Specified Number of Decimal Places</h3>
<p>When the second argument <code>ndigits</code> is provided, the same rule applies to the digit at that position.</p>
<ol>
<li><code>round(1.25, 1)</code> – The digit in the tenths place is 2, and the next digit is 5 (exactly halfway). The two possible results are 1.2 and 1.3. Since 2 is even, the result is <strong>1.2</strong>.</li>
<li><code>round(1.35, 1)</code> – The digit in the tenths place is 3, and the next digit is 5. The two possible results are 1.3 and 1.4. Since 4 is even, the result is <strong>1.4</strong>.</li>
<li><code>round(2.675, 2)</code> – This is a classic pitfall. Due to binary floating-point representation, <code>2.675</code> is actually stored as <code>2.6749999999999998</code>, so the result is <strong>2.67</strong>, not 2.68. This is not a banker’s rounding issue but a floating-point precision artifact.</li>
</ol>
<h2 id="counter-examples">Counter-Examples</h2>
<p>Understanding what banker’s rounding is <em>not</em> helps clarify its behavior. Here are common misconceptions and counter-examples:</p>
<ul>
<li><strong>Counter-example 1:</strong> <code>round(2.5)</code> does <em>not</em> return 3. Many expect half-up rounding, but Python returns 2.</li>
<li><strong>Counter-example 2:</strong> <code>round(1.25, 1)</code> does <em>not</em> return 1.3. It returns 1.2 because 2 is even.</li>
<li><strong>Counter-example 3:</strong> <code>round(-2.5)</code> does <em>not</em> return -3. It returns -2, following the same even-digit rule.</li>
<li><strong>Counter-example 4:</strong> <code>round(0.5)</code> returns 0, not 1, because 0 is even.</li>
</ul>
<p>These examples highlight that banker’s rounding is not symmetric in the way half-up is; it is symmetric in terms of bias reduction, not in terms of always rounding away from zero.</p>
<h2 id="convention-comparison-table">Convention Comparison Table</h2>
<p>The table below compares the most common rounding methods for a set of tie values. The “tie” column indicates numbers exactly halfway between two rounding candidates.</p>
<table>
<thead>
<tr>
<th>Value</th>
<th>Half-Up</th>
<th>Half-Down</th>
<th>Half-Even (Banker’s)</th>
<th>Half-Odd</th>
</tr>
</thead>
<tbody>
<tr>
<td>2.5</td>
<td>3</td>
<td>2</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>3.5</td>
<td>4</td>
<td>3</td>
<td>4</td>
<td>3</td>
</tr>
<tr>
<td>4.5</td>
<td>5</td>
<td>4</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>5.5</td>
<td>6</td>
<td>5</td>
<td>6</td>
<td>5</td>
</tr>
<tr>
<td>-2.5</td>
<td>-3</td>
<td>-2</td>
<td>-2</td>
<td>-3</td>
</tr>
<tr>
<td>-3.5</td>
<td>-4</td>
<td>-3</td>
<td>-4</td>
<td>-3</td>
</tr>
</tbody>
</table>
<p>As seen, half-even rounding produces a mix of even and odd results, whereas half-up always rounds away from zero (for positive numbers) and half-down always rounds toward zero. The half-even method minimizes cumulative error in sums and averages.</p>
<h2 id="standards-citation">Standards Citation</h2>
<p>Banker’s rounding is not an arbitrary choice; it is endorsed by several international standards and metrology guidelines.</p>
<ul>
<li><strong>IEEE 754</strong> (Standard for Floating-Point Arithmetic) specifies round-to-nearest-even as the default rounding mode for binary floating-point operations. Python’s <code>round()</code> for floats follows this standard.</li>
<li><strong>ISO 80000-1:2009</strong> (Quantities and units – Part 1: General) clause 7.3.4 recommends rounding to the nearest even digit when the discarded digit is exactly 5, to avoid systematic bias in statistical data.</li>
<li><strong>NIST SP 811</strong> (Guide for the Use of the International System of Units) section 7.2.2 discusses rounding rules and notes that “round half to even” is preferred for reducing rounding errors in calculations.</li>
<li><strong>GUM (JCGM 100:2008)</strong> – Evaluation of measurement data – Guide to the expression of uncertainty in measurement, clause 7.2.6, advises using a rounding rule that does not introduce bias, implicitly supporting half-even.</li>
</ul>
<p>These standards are used in scientific, engineering, and financial contexts to ensure that rounding does not distort results, especially when many numbers are rounded in a series.</p>
<h2 id="common-mistakes">Common Mistakes</h2>
<p>Even experienced programmers and scientists can fall into traps when using <code>round()</code>. Here are the most frequent errors:</p>
<ul>
<li><strong>Assuming half-up rounding:</strong> Many expect <code>round(2.5)</code> to be 3. Always verify the tie-breaking rule in your language or tool.</li>
<li><strong>Ignoring floating-point representation:</strong> Numbers like <code>2.675</code> are not stored exactly. The result of <code>round(2.675, 2)</code> is 2.67, not 2.68, due to binary approximation, not the rounding rule.</li>
<li><strong>Using <code>round()</code> for financial calculations:</strong> For currency, use the <code>decimal</code> module with an explicit rounding mode (e.g., <code>ROUND_HALF_UP</code>) to match legal or accounting requirements.</li>
<li><strong>Confusing <code>round()</code> with <code>int()</code> or <code>floor()</code>:</strong> <code>int(2.5)</code> truncates to 2, but <code>round(2.5)</code> also gives 2, which can mask the difference. For negative numbers, <code>int(-2.5)</code> gives -2, while <code>round(-2.5)</code> also gives -2, but for other values they diverge.</li>
<li><strong>Not considering the second argument:</strong> <code>round(2.5)</code> and <code>round(2.5, 0)</code> are equivalent, but <code>round(2.5, 1)</code> would round to 2.5 (no tie).</li>
</ul>
<h2 id="software-behavior-note">Software Behavior Note</h2>
<p>Python is not alone in using banker’s rounding. Many programming languages and tools adopt this convention for floating-point operations:</p>
<ul>
<li><strong>Python:</strong> <code>round()</code> uses round half to even for floats and for the <code>decimal</code> module when <code>ROUND_HALF_EVEN</code> is set (the default).</li>
<li><strong>JavaScript:</strong> <code>Math.round()</code> uses half-up for positive numbers and half-down for negative numbers (i.e., it rounds toward +∞). This is different from Python.</li>
<li><strong>Java:</strong> <code>Math.round()</code> uses half-up (rounds toward positive infinity for ties). However, <code>BigDecimal</code> allows explicit rounding modes.</li>
<li><strong>C/C++:</strong> The <code>round()</code> function in the standard library uses half-away-from-zero, but <code>rint()</code> and <code>nearbyint()</code> use the current rounding mode, which defaults to round-to-nearest-even.</li>
<li><strong>Excel:</strong> <code>ROUND()</code> uses half-up, while <code>ROUNDHALFEVEN()</code> is available in some versions.</li>
</ul>
<p>This inconsistency across software is a common source of confusion. Always check the documentation for the specific language or tool you are using.</p>
<h2 id="quick-reference-table">Quick Reference Table</h2>
<p>Here is a quick reference for common <code>round()</code> calls in Python and their results:</p>
<table>
<thead>
<tr>
<th>Expression</th>
<th>Result</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>round(2.5)</code></td>
<td>2</td>
<td>2 is even</td>
</tr>
<tr>
<td><code>round(3.5)</code></td>
<td>4</td>
<td>4 is even</td>
</tr>
<tr>
<td><code>round(4.5)</code></td>
<td>4</td>
<td>4 is even</td>
</tr>
<tr>
<td><code>round(5.5)</code></td>
<td>6</td>
<td>6 is even</td>
</tr>
<tr>
<td><code>round(1.25, 1)</code></td>
<td>1.2</td>
<td>2 is even</td>
</tr>
<tr>
<td><code>round(1.35, 1)</code></td>
<td>1.4</td>
<td>4 is even</td>
</tr>
<tr>
<td><code>round(-2.5)</code></td>
<td>-2</td>
<td>2 is even</td>
</tr>
<tr>
<td><code>round(-3.5)</code></td>
<td>-4</td>
<td>4 is even</td>
</tr>
</tbody>
</table>
<h2 id="sources-further-reading">Sources &amp; Further Reading</h2>
<p>For deeper understanding, consult the following authoritative resources:</p>
<ul>
<li>Python Documentation: <a href="https://docs.python.org/3/library/functions.html#round">Built-in Functions – round()</a></li>
<li>IEEE 754-2019: Standard for Floating-Point Arithmetic</li>
<li>ISO 80000-1:2009: Quantities and units – Part 1: General</li>
<li>NIST SP 811: Guide for the Use of the International System of Units (SI)</li>
<li>JCGM 100:2008: Evaluation of measurement data – Guide to the expression of uncertainty in measurement (GUM)</li>
</ul>
<p>These references provide the formal basis for rounding conventions and are essential for anyone working in metrology, data science, or scientific computing.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/why-pythons-round-uses-bankers-rounding/">Why Python’s round() Uses Banker’s Rounding: A Precision Reference</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://significantfigurescalculator.com/tools-code/python/why-pythons-round-uses-bankers-rounding/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Rounding to Significant Figures in Python: Precision, Pitfalls, and Best Practices</title>
		<link>https://significantfigurescalculator.com/tools-code/python/rounding-to-significant-figures-python/</link>
					<comments>https://significantfigurescalculator.com/tools-code/python/rounding-to-significant-figures-python/#respond</comments>
		
		<dc:creator><![CDATA[Tommy C. Moran]]></dc:creator>
		<pubDate>Sun, 02 Aug 2026 05:07:44 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[ASTM E29]]></category>
		<category><![CDATA[GUM]]></category>
		<category><![CDATA[precision]]></category>
		<category><![CDATA[rounding]]></category>
		<category><![CDATA[significant figures]]></category>
		<guid isPermaLink="false">http://significantfigurescalculator.test/uncategorized/rounding-to-significant-figures-python/</guid>

					<description><![CDATA[<p>Learn how to round numbers to a specified number of significant figures in Python, including the pitfalls of binary floating-point, banker's rounding, and standards-based approaches.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/rounding-to-significant-figures-python/">Rounding to Significant Figures in Python: Precision, Pitfalls, and Best Practices</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In scientific computing, engineering, and data analysis, rounding to a specified number of significant figures is a fundamental operation. Python, with its rich ecosystem, offers several ways to perform this task, but the language&#8217;s default behavior can be counterintuitive and may not align with established standards. This article serves as a comprehensive reference for precision and rounding, providing clear rules, worked examples, common pitfalls, and standards citations. Whether you are a student, engineer, or educator, this guide will help you achieve accurate and defensible rounding in Python.</p>
<h2 id="rule-statement">Rule Statement</h2>
<p>The rule for rounding to <em>n</em> significant figures is straightforward: identify the first <em>n</em> significant digits (non-zero digits, with leading zeros ignored) and round the number to that place value. If the digit immediately after the <em>n</em>-th significant digit is less than 5, truncate; if it is 5 or greater, round up. However, the handling of the digit 5 itself is subject to convention—some methods round half up, others round half to even (banker&#8217;s rounding), and some round half down. In Python, the built-in <code>round()</code> function uses banker&#8217;s rounding (round half to even) for binary floating-point numbers, which often surprises users.</p>
<p>For example, rounding 3.14159 to 3 significant figures yields 3.14, because the fourth significant digit is 1 (less than 5). Rounding 2.675 to 3 significant figures might be expected to give 2.68, but due to binary representation, <code>round(2.675, 2)</code> returns 2.67—a classic pitfall. To round to significant figures, one must first determine the position of the last significant digit and then apply the chosen rounding rule.</p>
<h2 id="worked-examples">Worked Examples</h2>
<p>Let&#8217;s explore practical Python code for rounding to a given number of significant figures. We&#8217;ll use the <code>Decimal</code> module for exact decimal arithmetic and a custom function for floating-point numbers.</p>
<h3 id="using-the-decimal-module">Using the Decimal Module</h3>
<p>The <code>decimal</code> module provides exact decimal representation and supports rounding modes like <code>ROUND_HALF_UP</code> and <code>ROUND_HALF_EVEN</code>. Here&#8217;s a function that rounds a float to <em>n</em> significant figures using Decimal:</p>
<pre><code>from decimal import Decimal, getcontext

def round_sig_decimal(value, sig_figs):
    if value == 0:
        return Decimal(0)
    d = Decimal(str(value))
    # Find the exponent of the first significant digit
    exponent = d.adjusted() - sig_figs + 1
    quant = Decimal(1).scaleb(exponent)
    return d.quantize(quant, rounding=ROUND_HALF_UP)
</code></pre>
<p>For example, <code>round_sig_decimal(3.14159, 3)</code> returns <code>Decimal('3.14')</code>, and <code>round_sig_decimal(2.675, 3)</code> returns <code>Decimal('2.68')</code> because the decimal string representation preserves the intended value.</p>
<h3 id="using-floating-point-arithmetic">Using Floating-Point Arithmetic</h3>
<p>For floating-point numbers, we can use <code>round()</code> after scaling. The following function works but is susceptible to binary rounding errors:</p>
<pre><code>def round_sig_float(value, sig_figs):
    if value == 0:
        return 0.0
    import math
    exponent = math.floor(math.log10(abs(value))) - sig_figs + 1
    factor = 10 ** exponent
    return round(value / factor) * factor
</code></pre>
<p>This method often works for values with exact binary representations, but fails for others. For instance, <code>round_sig_float(2.675, 3)</code> returns 2.67 due to the binary representation of 2.675 as 2.6749999999999998. The Decimal approach is recommended for critical applications.</p>
<h2 id="counter-examples">Counter-Examples</h2>
<p>Common errors arise from misunderstanding Python&#8217;s rounding behavior and floating-point representation.</p>
<ul>
<li><strong>Counter-Example 1:</strong> Using <code>round(2.675, 2)</code> expecting 2.68. Python returns 2.67 because 2.675 is stored as 2.6749999999999998, and the nearest representable value to the halfway point is slightly less.</li>
<li><strong>Counter-Example 2:</strong> Using <code>round(2.5)</code> expecting 3. Python&#8217;s banker&#8217;s rounding returns 2, because it rounds to the nearest even integer.</li>
<li><strong>Counter-Example 3:</strong> Rounding to significant figures by first rounding to a fixed number of decimal places. For example, rounding 0.0001234 to 2 significant figures by <code>round(0.0001234, 4)</code> gives 0.0001, which is wrong; the correct result is 0.00012.</li>
<li><strong>Counter-Example 4:</strong> Using <code>format(value, '.2e')</code> to round to 2 significant figures. This gives scientific notation, but the rounding is half-even as well, and the output is a string, not a numeric value.</li>
</ul>
<h2 id="convention-comparison-table">Convention Comparison Table</h2>
<p>Different rounding conventions are used across disciplines. The table below compares the most common methods for the digit 5.</p>
<table>
<thead>
<tr>
<th>Convention</th>
<th>Rule for 5</th>
<th>Example: 2.5 → 2 sig figs</th>
<th>Example: 3.5 → 2 sig figs</th>
</tr>
</thead>
<tbody>
<tr>
<td>Half-Up</td>
<td>Always round away from zero</td>
<td>2.5</td>
<td>3.5</td>
</tr>
<tr>
<td>Half-Even (Banker&#8217;s)</td>
<td>Round to nearest even digit</td>
<td>2.0</td>
<td>4.0</td>
</tr>
<tr>
<td>Half-Down</td>
<td>Always round toward zero</td>
<td>2.0</td>
<td>3.0</td>
</tr>
<tr>
<td>Half-Away-From-Zero</td>
<td>Round away from zero for positive numbers</td>
<td>3.0</td>
<td>4.0</td>
</tr>
</tbody>
</table>
<p>Python&#8217;s <code>round()</code> uses half-even for floats, while the <code>Decimal</code> module allows explicit selection. Many scientific standards, such as ASTM E29, specify half-up for test data conformance, but ISO 80000-1 permits half-up or half-even depending on the context.</p>
<h2 id="standards-citation">Standards Citation</h2>
<p>Several international standards govern rounding and significant figures:</p>
<ul>
<li><strong>ASTM E29-22</strong> – Standard Practice for Using Significant Digits in Test Data to Determine Conformance with Specifications. Section 6.2 describes the rounding method for test data, typically rounding half up.</li>
<li><strong>ISO 80000-1:2009</strong> – Quantities and units – Part 1: General. Clause 7.3.4 discusses rounding of numerical values, recommending that when the digit to be discarded is exactly 5, the preceding digit should be rounded to an even number (half-even) to avoid bias in statistical calculations.</li>
<li><strong>NIST SP 811</strong> – Guide for the Use of the International System of Units (SI). Section 7.2.5 provides guidance on rounding values to a specified number of digits, aligning with ISO 80000.</li>
<li><strong>JCGM 100:2008 (GUM)</strong> – Evaluation of measurement data – Guide to the expression of uncertainty in measurement. Clause 7.2.6 recommends rounding uncertainty values to one or two significant figures, with specific rules for rounding.</li>
</ul>
<p>When implementing rounding in Python, it is essential to know which standard applies to your field. For general scientific work, half-even is often preferred to reduce systematic error.</p>
<h2 id="common-mistakes">Common Mistakes</h2>
<ol>
<li><strong>Assuming <code>round()</code> rounds half up.</strong> Python&#8217;s <code>round()</code> uses banker&#8217;s rounding, which is not taught in many introductory courses.</li>
<li><strong>Ignoring binary floating-point representation.</strong> Values like 2.675 are not exact; always use <code>Decimal</code> or string conversion for critical rounding.</li>
<li><strong>Mixing decimal places with significant figures.</strong> Rounding to 2 decimal places is not the same as rounding to 2 significant figures, especially for numbers with different magnitudes.</li>
<li><strong>Using <code>format()</code> or f-strings for rounding.</strong> These produce strings and may use half-even; they are not suitable for further numeric calculations.</li>
<li><strong>Forgetting to handle zero and negative numbers.</strong> The exponent calculation must account for zero and sign.</li>
<li><strong>Applying rounding multiple times.</strong> Double rounding can introduce errors. Always round directly from the original value.</li>
</ol>
<h2 id="practice-problems">Practice Problems</h2>
<p>Test your understanding with these exercises. Use the Decimal approach for accurate results.</p>
<ol>
<li>Round 1234.5678 to 4 significant figures.</li>
<li>Round 0.0004567 to 2 significant figures.</li>
<li>Round -9876.5 to 3 significant figures using half-up.</li>
<li>Round 2.5 to 1 significant figure using half-even.</li>
<li>Round 100.0 to 2 significant figures.</li>
</ol>
<p>Answers: 1. 1235, 2. 0.00046, 3. -9880, 4. 2, 5. 1.0 × 10² (or 100 with two significant figures, but ambiguous without scientific notation).</p>
<h2 id="software-behavior-note">Software Behavior Note</h2>
<p>Python&#8217;s built-in <code>round()</code> is not suitable for significant-figure rounding due to its banker&#8217;s rounding and binary floating-point issues. The <code>decimal</code> module is the recommended tool for precise rounding. Additionally, third-party libraries like <code>numpy</code> offer <code>np.round()</code> which also uses half-even. For scientific computing, consider using <code>scipy</code> or <code>pandas</code> with custom functions. The <code>format()</code> specifier <code>'.*g'</code> can round to significant figures but returns a string and uses half-even. For example, <code>format(2.675, '.3g')</code> returns &#8216;2.67&#8217;. To achieve half-up rounding, you must use <code>Decimal</code> with <code>ROUND_HALF_UP</code>. Always be aware of the underlying representation and rounding mode to avoid subtle errors.</p>
<h2 id="quick-reference-table">Quick Reference Table</h2>
<p>Here are common values rounded to 3 significant figures using different methods:</p>
<table>
<thead>
<tr>
<th>Original</th>
<th>Half-Up</th>
<th>Half-Even</th>
<th>Python round()</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.2345</td>
<td>1.23</td>
<td>1.23</td>
<td>1.23</td>
</tr>
<tr>
<td>1.2355</td>
<td>1.24</td>
<td>1.24</td>
<td>1.24</td>
</tr>
<tr>
<td>1.2365</td>
<td>1.24</td>
<td>1.24</td>
<td>1.24</td>
</tr>
<tr>
<td>2.675</td>
<td>2.68</td>
<td>2.68</td>
<td>2.67</td>
</tr>
<tr>
<td>0.0001234</td>
<td>0.000123</td>
<td>0.000123</td>
<td>0.000123</td>
</tr>
</tbody>
</table>
<p>Note that for values without exact binary representation, Python&#8217;s <code>round()</code> may differ from decimal-based rounding.</p>
<h2 id="sources-further-reading">Sources &amp; Further Reading</h2>
<p>For deeper understanding, consult the following resources:</p>
<ul>
<li>ASTM E29-22: Standard Practice for Using Significant Digits in Test Data to Determine Conformance with Specifications.</li>
<li>ISO 80000-1:2009: Quantities and units – Part 1: General.</li>
<li>NIST SP 811: Guide for the Use of the International System of Units (SI).</li>
<li>JCGM 100:2008: Evaluation of measurement data – Guide to the expression of uncertainty in measurement (GUM).</li>
<li>Python documentation on <code>decimal</code> module and floating-point arithmetic.</li>
</ul>
<p>This article is part of our comprehensive <a href="#">precision and rounding reference</a>. Explore related topics like <a href="#">Banker&#8217;s Rounding</a>, <a href="#">Significant Figures in Scientific Notation</a>, and <a href="#">Rounding vs Significant Figures</a>.</p>
<p>The post <a href="https://significantfigurescalculator.com/tools-code/python/rounding-to-significant-figures-python/">Rounding to Significant Figures in Python: Precision, Pitfalls, and Best Practices</a> appeared first on <a href="https://significantfigurescalculator.com">SignificantFiguresCalculator</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://significantfigurescalculator.com/tools-code/python/rounding-to-significant-figures-python/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
