Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Error’d: Pickup Sticklers

      September 27, 2025

      From Prompt To Partner: Designing Your Custom AI Assistant

      September 27, 2025

      Microsoft unveils reimagined Marketplace for cloud solutions, AI apps, and more

      September 27, 2025

      Design Dialects: Breaking the Rules, Not the System

      September 27, 2025

      Building personal apps with open source and AI

      September 12, 2025

      What Can We Actually Do With corner-shape?

      September 12, 2025

      Craft, Clarity, and Care: The Story and Work of Mengchu Yao

      September 12, 2025

      Cailabs secures €57M to accelerate growth and industrial scale-up

      September 12, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The first browser with JavaScript landed 30 years ago

      September 27, 2025
      Recent

      The first browser with JavaScript landed 30 years ago

      September 27, 2025

      Four Different Meanings of “Template” a WordPress Pro Should Know

      September 27, 2025

      Adding Functionality with functions.php, a Heart of WordPress Theme Development

      September 27, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured
      Recent
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»News & Updates»CodeSOD: Round Strips

    CodeSOD: Round Strips

    August 12, 2025

    JavaScript is frequently surprising in terms of what functions it does not support. For example, while it has a Math.round function, that only rounds to the nearest integer, not an arbitrary precision. That’s no big deal, of course, as if you wanted to round to, say, four decimal places, you could write something like: Math.floor(n * 10000) / 10000.

    But in the absence of a built-in function to handle that means that many developers choose to reinvent the wheel. Ryan found this one.

    <span class="hljs-keyword">function</span> <span class="hljs-title function_">stripExtraNumbers</span>(<span class="hljs-params">num</span>) {
        <span class="hljs-comment">//check if the number's already okay</span>
        <span class="hljs-comment">//assume a whole number is valid</span>
        <span class="hljs-keyword">var</span> n2 = num.<span class="hljs-title function_">toString</span>();
        <span class="hljs-keyword">if</span>(n2.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">"."</span>) == -<span class="hljs-number">1</span>)  { <span class="hljs-keyword">return</span> num; }
        <span class="hljs-comment">//if it has numbers after the decimal point,</span>
        <span class="hljs-comment">//limit the number of digits after the decimal point to 4</span>
        <span class="hljs-comment">//we use parseFloat if strings are passed into the method</span>
        <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> num == <span class="hljs-string">"string"</span>){
            num = <span class="hljs-built_in">parseFloat</span>(num).<span class="hljs-title function_">toFixed</span>(<span class="hljs-number">4</span>);
        } <span class="hljs-keyword">else</span> {
            num = num.<span class="hljs-title function_">toFixed</span>(<span class="hljs-number">4</span>);
        }
        <span class="hljs-comment">//strip any extra zeros</span>
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">parseFloat</span>(num.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">replace</span>(<span class="hljs-regexp">/0*$/</span>,<span class="hljs-string">""</span>));
    }
    

    We start by turning the number into a string and checking for a decimal point. If it doesn’t have one, we’ve already rounded off, return the input. Now, we don’t trust our input, so if the input was already a string, we’ll parse it into a number. Once we know it’s a number, we can call toFixed, which returns a string rounded off to the correct number of decimal points.

    This is all very dumb. Just dumb. But it’s the last line which gets really dumb.

    toFixed returns a padded string, e.g. (10).toFixed(4) returns "10.0000". But this function doesn’t want those trailing zeros, so they convert our string num into a string, then use a regex to replace all of the trailing zeros, and then parse it back into a float.

    Which, of course, when storing the number as a number, we don’t really care about trailing zeros. That’s a formatting choice when we output it.

    I’m always impressed by a code sample where every single line is wrong. It’s like a little treat. In this case, it even gets me a sense of how it evolved from little snippets of misunderstood code. The regex to remove trailing zeros in some other place in this developer’s experience led to degenerate cases where they had output like 10., so they also knew they needed to have the check at the top to see if the input had a fractional part. Which the only way they knew to do that was by looking for a . in a string (have fun internationalizing that!). They also clearly don’t have a good grasp on types, so it makes sense that they have the extra string check, just to be on the safe side (though it’s worth noting that parseFloat is perfectly happy to run on a value that’s already a float).

    This all could be a one-liner, or maybe two if you really need to verify your types. Yet here we are, with a delightfully wrong way to do everything.

    [Advertisement]
    Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleLaravel’s UsePolicy Attribute: Explicit Authorization Control
    Next Article Building a Blended Material Shader in WebGL with Solid.js

    Related Posts

    News & Updates

    Building personal apps with open source and AI

    September 12, 2025
    News & Updates

    What Can We Actually Do With corner-shape?

    September 12, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    LLMs Can Now Reason Beyond Language: Researchers Introduce Soft Thinking to Replace Discrete Tokens with Continuous Concept Embeddings

    Machine Learning

    For Manufacturing Leaders: Rethink Aftermarket Service with AI at Dreamforce

    Development

    They’re coming for your data: What are infostealers and how do I stay safe?

    Development

    Hello 0-Days, My Old Friend: A 2024 Zero-Day Exploitation Analysis

    Security

    Highlights

    Why AI agents need a protocol like MCP to reach their potential

    May 8, 2025

    AI agents have been all the rage over the last several months, which has led…

    100,000+ WordPress Sites Exposed to Privilege Escalation Attacks via MCP AI Engine

    June 19, 2025

    Why GIGL needs a UX redesign

    May 19, 2025

    3 hidden Pixel camera features that can instantly take your videos to the next level

    September 3, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.