Get Number of Decimal Places with Javascript












2















How would I calculate the number of decimal places (not digits) of a real number with Javascript?



function countDecimals(number) {

}


For example, given 245.395, it should return 3.










share|improve this question




















  • 1





    What should 245.0 return?

    – RobG
    Nov 22 '14 at 21:32
















2















How would I calculate the number of decimal places (not digits) of a real number with Javascript?



function countDecimals(number) {

}


For example, given 245.395, it should return 3.










share|improve this question




















  • 1





    What should 245.0 return?

    – RobG
    Nov 22 '14 at 21:32














2












2








2








How would I calculate the number of decimal places (not digits) of a real number with Javascript?



function countDecimals(number) {

}


For example, given 245.395, it should return 3.










share|improve this question
















How would I calculate the number of decimal places (not digits) of a real number with Javascript?



function countDecimals(number) {

}


For example, given 245.395, it should return 3.







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '14 at 21:40









Andrei Volgin

34.4k53150




34.4k53150










asked Nov 22 '14 at 20:49









OctocatOctocat

1741315




1741315








  • 1





    What should 245.0 return?

    – RobG
    Nov 22 '14 at 21:32














  • 1





    What should 245.0 return?

    – RobG
    Nov 22 '14 at 21:32








1




1





What should 245.0 return?

– RobG
Nov 22 '14 at 21:32





What should 245.0 return?

– RobG
Nov 22 '14 at 21:32












6 Answers
6






active

oldest

votes


















2














Like this:



var val = 37.435345;
var countDecimals = function(value) {
if (Math.floor(value) !== value)
return value.toString().split(".")[1].length || 0;
return 0;
}
countDecimals(val);





share|improve this answer































    3














    The main idea is to convert a number to string and get the index of "."



    var x = 13.251256;
    var text = x.toString();
    var index = text.indexOf(".");
    alert(text.length - index - 1);





    share|improve this answer































      0














      You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:



      function countPlaces(num) {
      var sep = String(23.32).match(/D/)[0];
      var b = String(num).split(sep);
      return b[1]? b[1].length : 0;
      }

      console.log(countPlaces(2.343)); // 3
      console.log(countPlaces(2.3)); // 1
      console.log(countPlaces(343.0)); // 0
      console.log(countPlaces(343)); // 0





      share|improve this answer































        0














        Here is a method that does not rely on converting anything to string:



        function getDecimalPlaces(x,watchdog)
        {
        x = Math.abs(x);
        watchdog = watchdog || 20;
        var i = 0;
        while (x % 1 > 0 && i < watchdog)
        {
        i++;
        x = x*10;
        }
        return i;
        }


        Note that the count will not go beyond watchdog value (defaults to 20).






        share|improve this answer































          0














          var value = 888;
          var valueLength = value.toString().length;





          share|improve this answer



















          • 1





            Please add some explanation and context.

            – mjk
            Nov 23 '18 at 4:45



















          0














          Based on Gosha_Fighten's solution, for compatibility with integers:



          function countPlaces(num) {
          var text = num.toString();
          var index = text.indexOf(".");
          return index == -1 ? 0 : (text.length - index - 1);
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27082377%2fget-number-of-decimal-places-with-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            6 Answers
            6






            active

            oldest

            votes








            6 Answers
            6






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Like this:



            var val = 37.435345;
            var countDecimals = function(value) {
            if (Math.floor(value) !== value)
            return value.toString().split(".")[1].length || 0;
            return 0;
            }
            countDecimals(val);





            share|improve this answer




























              2














              Like this:



              var val = 37.435345;
              var countDecimals = function(value) {
              if (Math.floor(value) !== value)
              return value.toString().split(".")[1].length || 0;
              return 0;
              }
              countDecimals(val);





              share|improve this answer


























                2












                2








                2







                Like this:



                var val = 37.435345;
                var countDecimals = function(value) {
                if (Math.floor(value) !== value)
                return value.toString().split(".")[1].length || 0;
                return 0;
                }
                countDecimals(val);





                share|improve this answer













                Like this:



                var val = 37.435345;
                var countDecimals = function(value) {
                if (Math.floor(value) !== value)
                return value.toString().split(".")[1].length || 0;
                return 0;
                }
                countDecimals(val);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 22 '14 at 20:51









                Alex FilatovAlex Filatov

                1,76232228




                1,76232228

























                    3














                    The main idea is to convert a number to string and get the index of "."



                    var x = 13.251256;
                    var text = x.toString();
                    var index = text.indexOf(".");
                    alert(text.length - index - 1);





                    share|improve this answer




























                      3














                      The main idea is to convert a number to string and get the index of "."



                      var x = 13.251256;
                      var text = x.toString();
                      var index = text.indexOf(".");
                      alert(text.length - index - 1);





                      share|improve this answer


























                        3












                        3








                        3







                        The main idea is to convert a number to string and get the index of "."



                        var x = 13.251256;
                        var text = x.toString();
                        var index = text.indexOf(".");
                        alert(text.length - index - 1);





                        share|improve this answer













                        The main idea is to convert a number to string and get the index of "."



                        var x = 13.251256;
                        var text = x.toString();
                        var index = text.indexOf(".");
                        alert(text.length - index - 1);






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 22 '14 at 20:53









                        Gosha_FightenGosha_Fighten

                        2,43411222




                        2,43411222























                            0














                            You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:



                            function countPlaces(num) {
                            var sep = String(23.32).match(/D/)[0];
                            var b = String(num).split(sep);
                            return b[1]? b[1].length : 0;
                            }

                            console.log(countPlaces(2.343)); // 3
                            console.log(countPlaces(2.3)); // 1
                            console.log(countPlaces(343.0)); // 0
                            console.log(countPlaces(343)); // 0





                            share|improve this answer




























                              0














                              You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:



                              function countPlaces(num) {
                              var sep = String(23.32).match(/D/)[0];
                              var b = String(num).split(sep);
                              return b[1]? b[1].length : 0;
                              }

                              console.log(countPlaces(2.343)); // 3
                              console.log(countPlaces(2.3)); // 1
                              console.log(countPlaces(343.0)); // 0
                              console.log(countPlaces(343)); // 0





                              share|improve this answer


























                                0












                                0








                                0







                                You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:



                                function countPlaces(num) {
                                var sep = String(23.32).match(/D/)[0];
                                var b = String(num).split(sep);
                                return b[1]? b[1].length : 0;
                                }

                                console.log(countPlaces(2.343)); // 3
                                console.log(countPlaces(2.3)); // 1
                                console.log(countPlaces(343.0)); // 0
                                console.log(countPlaces(343)); // 0





                                share|improve this answer













                                You can use a simple function that splits on the decimal place (if there is one) and counts the digits after that. Since the decimal place can be represented by '.' or ',' (or maybe some other character), you can test for that and use the appropriate one:



                                function countPlaces(num) {
                                var sep = String(23.32).match(/D/)[0];
                                var b = String(num).split(sep);
                                return b[1]? b[1].length : 0;
                                }

                                console.log(countPlaces(2.343)); // 3
                                console.log(countPlaces(2.3)); // 1
                                console.log(countPlaces(343.0)); // 0
                                console.log(countPlaces(343)); // 0






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 22 '14 at 21:39









                                RobGRobG

                                98.1k19106145




                                98.1k19106145























                                    0














                                    Here is a method that does not rely on converting anything to string:



                                    function getDecimalPlaces(x,watchdog)
                                    {
                                    x = Math.abs(x);
                                    watchdog = watchdog || 20;
                                    var i = 0;
                                    while (x % 1 > 0 && i < watchdog)
                                    {
                                    i++;
                                    x = x*10;
                                    }
                                    return i;
                                    }


                                    Note that the count will not go beyond watchdog value (defaults to 20).






                                    share|improve this answer




























                                      0














                                      Here is a method that does not rely on converting anything to string:



                                      function getDecimalPlaces(x,watchdog)
                                      {
                                      x = Math.abs(x);
                                      watchdog = watchdog || 20;
                                      var i = 0;
                                      while (x % 1 > 0 && i < watchdog)
                                      {
                                      i++;
                                      x = x*10;
                                      }
                                      return i;
                                      }


                                      Note that the count will not go beyond watchdog value (defaults to 20).






                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        Here is a method that does not rely on converting anything to string:



                                        function getDecimalPlaces(x,watchdog)
                                        {
                                        x = Math.abs(x);
                                        watchdog = watchdog || 20;
                                        var i = 0;
                                        while (x % 1 > 0 && i < watchdog)
                                        {
                                        i++;
                                        x = x*10;
                                        }
                                        return i;
                                        }


                                        Note that the count will not go beyond watchdog value (defaults to 20).






                                        share|improve this answer













                                        Here is a method that does not rely on converting anything to string:



                                        function getDecimalPlaces(x,watchdog)
                                        {
                                        x = Math.abs(x);
                                        watchdog = watchdog || 20;
                                        var i = 0;
                                        while (x % 1 > 0 && i < watchdog)
                                        {
                                        i++;
                                        x = x*10;
                                        }
                                        return i;
                                        }


                                        Note that the count will not go beyond watchdog value (defaults to 20).







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Apr 19 '15 at 10:36









                                        jahujahu

                                        3,64812347




                                        3,64812347























                                            0














                                            var value = 888;
                                            var valueLength = value.toString().length;





                                            share|improve this answer



















                                            • 1





                                              Please add some explanation and context.

                                              – mjk
                                              Nov 23 '18 at 4:45
















                                            0














                                            var value = 888;
                                            var valueLength = value.toString().length;





                                            share|improve this answer



















                                            • 1





                                              Please add some explanation and context.

                                              – mjk
                                              Nov 23 '18 at 4:45














                                            0












                                            0








                                            0







                                            var value = 888;
                                            var valueLength = value.toString().length;





                                            share|improve this answer













                                            var value = 888;
                                            var valueLength = value.toString().length;






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Nov 23 '18 at 1:43









                                            Jun BinJun Bin

                                            646




                                            646








                                            • 1





                                              Please add some explanation and context.

                                              – mjk
                                              Nov 23 '18 at 4:45














                                            • 1





                                              Please add some explanation and context.

                                              – mjk
                                              Nov 23 '18 at 4:45








                                            1




                                            1





                                            Please add some explanation and context.

                                            – mjk
                                            Nov 23 '18 at 4:45





                                            Please add some explanation and context.

                                            – mjk
                                            Nov 23 '18 at 4:45











                                            0














                                            Based on Gosha_Fighten's solution, for compatibility with integers:



                                            function countPlaces(num) {
                                            var text = num.toString();
                                            var index = text.indexOf(".");
                                            return index == -1 ? 0 : (text.length - index - 1);
                                            }





                                            share|improve this answer




























                                              0














                                              Based on Gosha_Fighten's solution, for compatibility with integers:



                                              function countPlaces(num) {
                                              var text = num.toString();
                                              var index = text.indexOf(".");
                                              return index == -1 ? 0 : (text.length - index - 1);
                                              }





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                Based on Gosha_Fighten's solution, for compatibility with integers:



                                                function countPlaces(num) {
                                                var text = num.toString();
                                                var index = text.indexOf(".");
                                                return index == -1 ? 0 : (text.length - index - 1);
                                                }





                                                share|improve this answer













                                                Based on Gosha_Fighten's solution, for compatibility with integers:



                                                function countPlaces(num) {
                                                var text = num.toString();
                                                var index = text.indexOf(".");
                                                return index == -1 ? 0 : (text.length - index - 1);
                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Dec 12 '18 at 9:13









                                                LePatayLePatay

                                                9217




                                                9217






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27082377%2fget-number-of-decimal-places-with-javascript%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Ottavio Pratesi

                                                    Tricia Helfer

                                                    15 giugno