Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Round a Number Down in Python?

#1
How to Round a Number Down in Python?

<div><p><strong>Problem Formulation</strong>: Given a float number. How to round the float down in Python?</p>
<p>Here are some examples of what you want to accomplish:</p>
<ul>
<li><code>42.52 --> 42</code></li>
<li><code>21.99999 --> 22</code></li>
<li><code>-0.1 --> -1</code></li>
<li><code>-2 --> -2</code></li>
</ul>
<p><strong>Solution</strong>: If you have little time, here’s the most straightforward answer:</p>
<p class="has-pale-cyan-blue-background-color has-background">To round a positive or negative number <code>x</code> down in Python, apply <a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-integer-division/" data-type="post" data-id="91" target="_blank">integer division</a> <code>//</code> to <code>x</code> and divide by <code>1</code>. Specifically, the expression <code>x//1</code> will first perform normal float division and then throw away the remainder—effectively “rounding <code>x</code> down”. </p>
<p>In general, there are multiple ways to round a float number <code>x</code> down in Python:</p>
<ul>
<li><strong>Vanilla Python</strong>: The expression <code>x//1</code> will first perform normal division and then skip the remainder—effectively “rounding <code>x</code> down”.</li>
<li><strong>Round down</strong>: The <code>math.floor(x)</code> function rounds number <code>x</code> down to the next full integer.</li>
<li><strong>Round down (float representation)</strong>: Alternatively, <code>numpy.floor(x)</code> rounds down and returns a float representation of the next full integer (e.g., <code>2.0</code> instead of <code>2</code>).</li>
<li><strong>Round up</strong>: The <code>math.ceil(x)</code> function rounds number <code>x</code> up to the next full integer. </li>
<li><strong>Round up and down</strong>: The Python built-in <code>round(x)</code> function rounds <code>x</code> up and down to the closest full integer.</li>
</ul>
<p>Let’s dive into each of those and more options in the remaining article. I guarantee you’ll get out of it having learned at least a few new Python tricks in the process!</p>
<h2>Method 1: Integer Division (x//1)</h2>
<p class="has-global-color-8-background-color has-background">The most straightforward way to round a positive or negative number <code>x</code> down in Python is to use <a href="https://blog.finxter.com/daily-python-puzzle-integer-division/" data-type="post" data-id="91" target="_blank" rel="noreferrer noopener">integer division</a> <code>//</code> by <code>1</code>. The expression <code>x//1</code> will first perform normal division and then skip the remainder—effectively “rounding <code>x</code> down”. </p>
<p>For example:</p>
<ul>
<li><code>42.52//1 == 42</code></li>
<li><code>21.99//1 == 21</code></li>
<li><code>-0.1//1 == -1</code></li>
<li><code>-2//1 == -2</code></li>
</ul>
<p>This trick works for positive and negative numbers—beautiful isn’t it? <img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f33b.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Here are a couple of Python code examples:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def round_down(x): return x//1 print(round_down(42.52))
# 42 print(round_down(21.99999))
# 21 print(round_down(-0.1))
# -1 print(round_down(-2))
# -2
</pre>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f393.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Info</strong>: The double-backslash <code>//</code> operator performs integer division and the single-backslash <code>/</code> operator performs float division. An example for integer division is <code>40//11 = 3</code>. An example for float division is <code>40/11 = 3.6363636363636362</code>.</p>
<p>Feel free to watch the following video for some repetition or learning:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Division Deep Dive" width="780" height="439" src="https://www.youtube.com/embed/WK5Q60qME-8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Method 2: math.floor()</h2>
<p>To round a number down in Python, import the <code>math</code> library with <code>import math</code>, and call <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-math-functions/" data-type="post" data-id="69128" target="_blank">math.floor(number)</a></code>.</p>
<p>The function returns the floor of the specified <code>number</code> that is defined as the largest integer <a rel="noreferrer noopener" href="https://blog.finxter.com/python-less-than-or-equal-to/" data-type="post" data-id="30938" target="_blank">less than or equal</a> to <code>number</code>.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: The <code>math.floor()</code> function correctly rounds down floats to the next-smaller full integer for <strong><em>positive and negative integers</em></strong>.</p>
<p>Here’s a code example that rounds our five numbers down to the next-smaller full integer: </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math print(math.floor(42.52))
# 42 print(math.floor(21.99999))
# 21 print(math.floor(-0.1))
# -1 print(math.floor(-2))
# -2
</pre>
<p>The following video shows the <code>math.floor()</code> as well as the <code>math.ceil()</code> functions — feel free to watch it to gain a deeper understanding:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Math floor(), ceil(), trunc(), and modf()" width="780" height="585" src="https://www.youtube.com/embed/MZb2liD3Iuw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Method 3: np.floor()</h2>
<p>To round a number down in Python, import the <a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" data-type="post" data-id="1356" target="_blank">NumPy library</a> with <code>import numpy as np</code>, and call <code>np.floor(number)</code>.</p>
<p>The function returns the floor of the specified <code>number</code> that is defined as the largest integer <a rel="noreferrer noopener" href="https://blog.finxter.com/python-less-than-or-equal-to/" data-type="URL" data-id="https://blog.finxter.com/python-less-than-or-equal-to/" target="_blank">less than or equal</a> to <code>number</code>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np print(np.floor(42.52))
# 42.0 print(np.floor(21.99999))
# 21.0 print(np.floor(-0.1))
# -1.0 print(np.floor(-2))
# -2.0
</pre>
<p class="has-global-color-8-background-color has-background">Both <code>math.floor()</code> and <code>np.floor()</code> round down to the next full integer. The difference between <code>math.floor()</code> and <code>np.floor()</code> is that the former returns an integer and the latter returns a float value.</p>
<h2>Method 4: int(x)</h2>
<p class="has-global-color-8-background-color has-background">Use the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-int-function/" data-type="post" data-id="22715" target="_blank">int(x)</a></code> function to round a positive number <code>x>0</code> down to the next integer. For example, <code>int(42.99)</code> rounds <code>42.99</code> down to the answer <code>42</code>. </p>
<p>Here’s an example for positive numbers where <code>int()</code> will round down:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(int(42.52))
# 42 print(int(21.99999))
# 21
</pre>
<p>However, if the number is negative, the function <code>int()</code> will round up! Here’s an example for negative numbers:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(int(-0.1))
# 0 print(int(-2))
# -2
</pre>
<p>Before I show you how to overcome this limitation for negative numbers, feel free to watch my explainer video on this function here:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python int() Function" width="780" height="439" src="https://www.youtube.com/embed/JKDzKWtlaQE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Method 5: int(x) – bool(x%1)</h2>
<p>You can also use the following vanilla Python snippet to round a number <code>x</code> down to the next full integer:</p>
<ul>
<li>If <code>x</code> is positive, round down by calling <code>int(x)</code>.</li>
<li>If <code>x</code> is negative, round up by calling <code>int(x) - bool(x%1)</code>. </li>
</ul>
<p><strong>Explanation</strong>: Any non-zero expression passed into the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-bool/" data-type="post" data-id="17841" target="_blank">bool()</a></code> function will yield <code>True</code> which is represented by integer 1. </p>
<p>The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-modulo/" data-type="post" data-id="104" target="_blank">modulo</a> expression <code>x%1</code> returns the decimal part of <code>x</code>. </p>
<ul>
<li>If it is non-zero, we subtract <code>bool(x%1) == 1</code>, i.e., we round down. </li>
<li>If it is zero (for whole numbers), we subtract <code>bool(x%1) == 0</code>, i.e., we’re already done.</li>
</ul>
<p>Here’s what this looks like in a simple Python function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def round_down(x): if x&lt;0: return int(x) - bool(x%1) return int(x) print(round_down(42.52))
# 42 print(round_down(21.99999))
# 21 print(round_down(-0.1))
# -1 print(round_down(-2))
# -2
</pre>
<p>Alternatively, you can use the following slight variation of the function definition:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def round_down(x): if x&lt;0: return int(x) - int(x)!=x return int(x)</pre>
<h2>Method 6: round()</h2>
<p><em>This method is probably not exactly what you want because it rounds a number up and down, depending on whether the number is closer to the smaller or larger next full integer. However, I’ll still mention it for comprehensibility.</em></p>
<hr class="wp-block-separator"/>
<p>Python’s built-in <code><a href="https://blog.finxter.com/python-round-a-simple-guide-with-video/" data-type="post" data-id="23673" target="_blank" rel="noreferrer noopener">round()</a></code> function takes two input arguments: </p>
<ul>
<li>a <code>number</code> and </li>
<li>an optional <code>precision</code> in decimal digits. </li>
</ul>
<p>It rounds the number to the given precision and returns the result. The return value has the same type as the input number—or integer if the <code>precision</code> argument is omitted. </p>
<p>Per default, the precision is set to 0 digits, so <code>round(3.14)</code> results in <code>3</code>.</p>
<p>Here are three examples using the <code>round()</code> function—that show that it doesn’t exactly solve our problem.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import math print(round(42.42))
# 42 print(round(21.00001))
# 21 print(round(-0.1))
# 0
</pre>
<p>Again, we have a video on the <code>round()</code> function — feel free to watch for maximum learning!</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python round() — A Helpful Interactive Guide" width="780" height="439" src="https://www.youtube.com/embed/B3P3dXpLoTk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
</div>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p>
<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts </em></strong>and<strong><em> boost your coding and analytical skills</em></strong>. You’ll learn about advanced Python features such as <em><strong>list comprehension</strong></em>, <strong><em>slicing</em></strong>, <strong><em>lambda functions</em></strong>, <strong><em>regular expressions</em></strong>, <strong><em>map </em></strong>and <strong><em>reduce </em></strong>functions, and <strong><em>slice assignments</em></strong>. </p>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<li>Use <strong>NumPy basics</strong> such as <em>array</em>, <em>shape</em>, <em>axis</em>, <em>type</em>, <em>broadcasting</em>, <em>advanced indexing</em>, <em>slicing</em>, <em>sorting</em>, <em>searching</em>, <em>aggregating</em>, and <em>statistics</em></li>
<li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<li>Create more <strong>advanced regular expressions</strong> using <em>grouping </em>and <em>named groups</em>, <em>negative lookaheads</em>, <em>escaped characters</em>, <em>whitespaces, character sets</em> (and <em>negative characters sets</em>), and <em>greedy/nongreedy operators</em></li>
<li>Understand a wide range of <strong>computer science topics</strong>, including <em>anagrams</em>, <em>palindromes</em>, <em>supersets</em>, <em>permutations</em>, <em>factorials</em>, <em>prime numbers</em>, <em>Fibonacci </em>numbers, <em>obfuscation</em>, <em>searching</em>, and <em>algorithmic sorting</em></li>
</ul>
<p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2022/04/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016