Search code examples
javascriptreactjsreact-nativenumbersrounding

How to round number in javascript if number has 0.04500001 as decimals?


I came across a number like this in a project :

Number

I was wondering whats the case for rounding up this kind of number in real world project and how to round the number when it has lots of zeros like this :

 {item.size - item.filled}

I also tried toFixed but it applies it to all generated numbers so other numbers which aren't in the format like this one , will also get zeros after decimals.

{(item.size - item.filled).toFixed(7)}

How can I round this kind of number only If it's like this and what would be the normal scenario in a real world project ? Should we just not display all the zeros in decimals ?


Solution

  • Here I wrote an answer to format all sort of rounding...

    Possible duplicate with "I'd like to round at most two decimal places, but only if necessary"...

    https://stackoverflow.com/questions/11832914/how-to-round-to-at-most-2-decimal-places-if-necessary/73831129#73831129

    This answer do the job : You can round Your number at any decimal and add "0" to obtain the format You want to reach.

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>roundPrecision</title>
        <script>
            class MyMath{
                static roundPrecision(number,precision,fillZeros){
                        // number You want to round
                        // precision nb of decimals
                        // fillZeros the number of 0 You want to add IF necessary!
                        // 0 = no fill with zeros.
                        let num = number;
                        let prec = precision;
                        let exp = Math.pow(10,prec);
                        let round = Math.round(number * exp)/exp
                        if (fillZeros>0){
                            return round.toFixed(fillZeros)
                            }
                        return round;
                    }
            }
        </script>
    </head>
    
    <body>
        <p class="myMath" id="field1"></p>
        <p class="myMath" id="field2"></p>
        <p class="myMath" id="field3"></p>
        <p class="myMath" id="field4"></p>
        <p class="myMath" id="field5"></p>
        <script>
            document.getElementById("field1").innerHTML = MyMath.roundPrecision(5,0,3); // 5.000
            document.getElementById("field2").innerHTML = MyMath.roundPrecision(Math.PI,2,4); // 3.1400
            document.getElementById("field3").innerHTML = MyMath.roundPrecision(2.4,1,2); // 2.40
            document.getElementById("field4").innerHTML = MyMath.roundPrecision(2.9,0,2);   // 3.00
            document.getElementById("field5").innerHTML = MyMath.roundPrecision(10,0,2); // 10.00
        </script>
    </body>
    </html>
    
        </script>
    </body>
    </html>