Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. JavaScript
  4. toLocaleString() works to insert commas in a asp.net textbox until I enter the eighth digit. The eight digit breaks the insertion of commas

toLocaleString() works to insert commas in a asp.net textbox until I enter the eighth digit. The eight digit breaks the insertion of commas

Scheduled Pinned Locked Moved JavaScript
asp-netcsharpjavascriptregexhelp
11 Posts 5 Posters 14 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Offline
    F Offline
    fig0000
    wrote on last edited by
    #1

    Hi, I am not the best at Javascript but have been using it more to avoid web forms postbacks at my users requests. The user also requested commas inserted in an numeric field (no decimal digits) as they type. I used toLocaleString(). The insertion of commas works fine until I get to the eighth digit. At that point the number shrinks in size and goes back to four digits, There is a valid comma in this but obviously I need to be able to put in more than 7 digitis. Here is the seven digit state of the field: 1,234,567 And here is the field when I add the number 8 to the end of the above number: 1,234 The following code fired from on the onkeyup event handles this number: var word = txtbox.value; word = word.replace(“,”, “”); let num = word; formatted = parseInt(String(num)).toLocaleString(); txtbox.value = formatted; I have also tried functions i found on web posts and regex values. Some cases didnt work at atll but many of the cases involving regex also seemed to break once the eighth digit is entered. Oddly all the examples I’ve seen on the web seem to involve no more than seven digits. I tried adding “en-us” to the toLocaleString() as well as setting maxiumnsignificantdigits to 9. The result was the same. 8 seems to be a magic number and the solution is probably buried in some obscure documentation somewhere. Any help would be appreciated. Neil

    Richard DeemingR 1 Reply Last reply
    0
    • F fig0000

      Hi, I am not the best at Javascript but have been using it more to avoid web forms postbacks at my users requests. The user also requested commas inserted in an numeric field (no decimal digits) as they type. I used toLocaleString(). The insertion of commas works fine until I get to the eighth digit. At that point the number shrinks in size and goes back to four digits, There is a valid comma in this but obviously I need to be able to put in more than 7 digitis. Here is the seven digit state of the field: 1,234,567 And here is the field when I add the number 8 to the end of the above number: 1,234 The following code fired from on the onkeyup event handles this number: var word = txtbox.value; word = word.replace(“,”, “”); let num = word; formatted = parseInt(String(num)).toLocaleString(); txtbox.value = formatted; I have also tried functions i found on web posts and regex values. Some cases didnt work at atll but many of the cases involving regex also seemed to break once the eighth digit is entered. Oddly all the examples I’ve seen on the web seem to involve no more than seven digits. I tried adding “en-us” to the toLocaleString() as well as setting maxiumnsignificantdigits to 9. The result was the same. 8 seems to be a magic number and the solution is probably buried in some obscure documentation somewhere. Any help would be appreciated. Neil

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      If you pass a string to the replace method, only the first match will be replaced:

      String.prototype.replace() - JavaScript | MDN[^]:

      A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the g flag, or use replaceAll()[^] instead.

      Given the input "1,234,567", after the replace(",", "") call, the value will be "1234,567". Passing that to parseInt will stop at the first non-numeric character, so the result will be 1234. Thus you need to replace:

      word = word.replace(",", "");

      with either:

      word = word.replace(/,/g, "");

      or:

      word = word.replaceAll(",", "");

      Demo[^]


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      F 1 Reply Last reply
      0
      • Richard DeemingR Richard Deeming

        If you pass a string to the replace method, only the first match will be replaced:

        String.prototype.replace() - JavaScript | MDN[^]:

        A string pattern will only be replaced once. To perform a global search and replace, use a regular expression with the g flag, or use replaceAll()[^] instead.

        Given the input "1,234,567", after the replace(",", "") call, the value will be "1234,567". Passing that to parseInt will stop at the first non-numeric character, so the result will be 1234. Thus you need to replace:

        word = word.replace(",", "");

        with either:

        word = word.replace(/,/g, "");

        or:

        word = word.replaceAll(",", "");

        Demo[^]


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        F Offline
        F Offline
        fig0000
        wrote on last edited by
        #3

        Thank you so much for the reply. It seems obvious now that I see it but you don't always see that there can be variations of functions until you accidently run into them. Sorry to pile on another question. This one is weirder as far as I can see. I don't know how many digits I may need so I tried putting in more than 8. I kept going past the eighth digit which worked using your fix. I kept going and got to

        12,345,678,901

        . Oddly when I added a "2" after this numg34 the "2" was simply ignored and did not appear in the text box at all. I did try doing some alerts but it seems that this last digit is not showing up as a typed key in the textbox, almost as if it is being ignored. Am I still missing some details or is there some further issue I'm not aware of. Thanks, Neil

        Richard DeemingR J 2 Replies Last reply
        0
        • F fig0000

          Thank you so much for the reply. It seems obvious now that I see it but you don't always see that there can be variations of functions until you accidently run into them. Sorry to pile on another question. This one is weirder as far as I can see. I don't know how many digits I may need so I tried putting in more than 8. I kept going past the eighth digit which worked using your fix. I kept going and got to

          12,345,678,901

          . Oddly when I added a "2" after this numg34 the "2" was simply ignored and did not appear in the text box at all. I did try doing some alerts but it seems that this last digit is not showing up as a typed key in the textbox, almost as if it is being ignored. Am I still missing some details or is there some further issue I'm not aware of. Thanks, Neil

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          That's odd - on the demo link I posted[^], I can get up to 1,234,567,890,123,456 without any issues. It then won't recognise any odd numbers; if I type an 7, it becomes an 8. There's an exhaustive explanation as to why on this StackOverflow thread[^]. Anything I type beyond that gets appended as 0. That's because the parsed number exceeds Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), so anything larger will have its least-significant digits truncated.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          F J 2 Replies Last reply
          0
          • F fig0000

            Thank you so much for the reply. It seems obvious now that I see it but you don't always see that there can be variations of functions until you accidently run into them. Sorry to pile on another question. This one is weirder as far as I can see. I don't know how many digits I may need so I tried putting in more than 8. I kept going past the eighth digit which worked using your fix. I kept going and got to

            12,345,678,901

            . Oddly when I added a "2" after this numg34 the "2" was simply ignored and did not appear in the text box at all. I did try doing some alerts but it seems that this last digit is not showing up as a typed key in the textbox, almost as if it is being ignored. Am I still missing some details or is there some further issue I'm not aware of. Thanks, Neil

            J Offline
            J Offline
            jsc42
            wrote on last edited by
            #5

            Your original question said (my emphasis):Could that be related to why you have issues putting in more than

            fig0000 wrote:

            I tried adding “en-us” to the toLocaleString() as well as setting maxiumnsignificantdigits to 9

            Could that be related to why you have issues putting in more than 8?

            F 1 Reply Last reply
            0
            • J jsc42

              Your original question said (my emphasis):Could that be related to why you have issues putting in more than

              fig0000 wrote:

              I tried adding “en-us” to the toLocaleString() as well as setting maxiumnsignificantdigits to 9

              Could that be related to why you have issues putting in more than 8?

              F Offline
              F Offline
              fig0000
              wrote on last edited by
              #6

              Thank you for replying. This inability to put 8 digits in has already been spotted by Mr. Deeming. With my lack of experience with Javascript I didn't realize that I needed to use "replaceall" instead of replace. To use tolocalstring I have to clear all the commas out of the field as I add new digits. I was using replace which only replaces the first comma meaning the other commma stays in field and the code rejects that comma and all the digits after it truncating the number when tolocatstring is used to fill the field. The new issue can be seen above from Mr. Demming which has to do with other issues. While we can get farther along he found that there is a point where negative digits are ignored and I've found some other issues. He suggested that I read a web page describing this problem but it's not clear that I can make it work as it is. I may have to write code that does not use tolocalstring and do brute force slicing and dicing to put the commas in the right place. I will look at his information and see what I have to do.

              J 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                That's odd - on the demo link I posted[^], I can get up to 1,234,567,890,123,456 without any issues. It then won't recognise any odd numbers; if I type an 7, it becomes an 8. There's an exhaustive explanation as to why on this StackOverflow thread[^]. Anything I type beyond that gets appended as 0. That's because the parsed number exceeds Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), so anything larger will have its least-significant digits truncated.


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                F Offline
                F Offline
                fig0000
                wrote on last edited by
                #7

                Mr. Deeming, I saw your experiments using very large numbers and the weird behavior with negative numbers and, as you said, eventual replacement of numbers with zeros. I will read the JS documentation you gave me. I will ask however it you found that this JS documentation helped you solve the problem or if a mystery to you and you have no fix for it. I ask because I am considering not using tolocalstring and all that and simply using brute force parsing of the number as it is typed (e.g. dividing the number of digits by three and using that to place the commas in through parsing code and not to local string). I hesitate to do this but it may be my only answer. Just let me know if, as it seems from your post, that you have been unable to solve the problem of weird behavior adding a high number of digits. You also describe a demo you set up to test this; is it possible for you to post it. Due to the high number of digits you were able to use, that may be enough for me to handle this cases I have in my code (I believe it don't need to use more than 12 digits which is far smaller than the example you showed us that worked. Thanks again for all your help. Neil

                Richard DeemingR 1 Reply Last reply
                0
                • F fig0000

                  Mr. Deeming, I saw your experiments using very large numbers and the weird behavior with negative numbers and, as you said, eventual replacement of numbers with zeros. I will read the JS documentation you gave me. I will ask however it you found that this JS documentation helped you solve the problem or if a mystery to you and you have no fix for it. I ask because I am considering not using tolocalstring and all that and simply using brute force parsing of the number as it is typed (e.g. dividing the number of digits by three and using that to place the commas in through parsing code and not to local string). I hesitate to do this but it may be my only answer. Just let me know if, as it seems from your post, that you have been unable to solve the problem of weird behavior adding a high number of digits. You also describe a demo you set up to test this; is it possible for you to post it. Due to the high number of digits you were able to use, that may be enough for me to handle this cases I have in my code (I believe it don't need to use more than 12 digits which is far smaller than the example you showed us that worked. Thanks again for all your help. Neil

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #8

                  fig0000 wrote:

                  You also describe a demo you set up to test this; is it possible for you to post it.

                  I've already posted the link twice - here it is a third time for luck: Demo[^] NB: If you need to support more digits than a JavaScript number can safely represent, then you've got two options: switch to using BigInt[^], or manually parse and format the number yourself. Here's a demo using BigInt: Demo[^]

                  const formatNumber = () => {
                  const word = txtbox.value.replaceAll(",", "");
                  const number = BigInt(word); // instead of parseInt(word)
                  const formatted = number.toLocaleString();
                  txtbox.value = formatted;
                  };

                  That doesn't suffer from the same problems as the original, since BigInt can support obscenely large numbers. Formatting the number manually is not quite as simple, but it can be done: Demo[^]

                  const formatNumber = () => {
                  const word = txtbox.value.replace(/[^0-9]/g, ""); // Strip out any non-numeric characters
                  const chars = word.split("").reverse(); // Get an array of characters from right to left

                  // Insert a comma after every third number:
                  for (let index = 3; index < chars.length; index += 4) {
                  	chars.splice(index, 0, ",");
                  }
                  
                  // Reverse the chars again, and convert back to a string:
                  txtbox.value = chars.reverse().join("");
                  

                  };


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    That's odd - on the demo link I posted[^], I can get up to 1,234,567,890,123,456 without any issues. It then won't recognise any odd numbers; if I type an 7, it becomes an 8. There's an exhaustive explanation as to why on this StackOverflow thread[^]. Anything I type beyond that gets appended as 0. That's because the parsed number exceeds Number.MAX_SAFE_INTEGER (9,007,199,254,740,991), so anything larger will have its least-significant digits truncated.


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    J Offline
                    J Offline
                    Jeremy Falcon
                    wrote on last edited by
                    #9

                    Thanks for handling this reply. Just a couple notes to help make the magic happen. parseInt should always have the second radix param specified. Otherwise, it'll attempt to guess it and not always possible to guess octal vs decimal, etc. It's still safer to use replace over replaceAll. Edge support is only a few years old, for instance. Adoption just be a slow thing. No need to convert the input to a string for parseInt. It's already a string. Check the fiddle below for proof. Annnnnnnnnnd, JS now has a data type called BigInt. Which won't help for floating points / money type inputs. But if you're looking to do this with a much larger integer... [Behold](https://jsfiddle.net/jfalcon/0y3vn5xr/21/)! Edit: Awww crap, I just read your BigInt post. Never mind. :laugh: :laugh: :laugh:

                    Jeremy Falcon

                    1 Reply Last reply
                    0
                    • F fig0000

                      Thank you for replying. This inability to put 8 digits in has already been spotted by Mr. Deeming. With my lack of experience with Javascript I didn't realize that I needed to use "replaceall" instead of replace. To use tolocalstring I have to clear all the commas out of the field as I add new digits. I was using replace which only replaces the first comma meaning the other commma stays in field and the code rejects that comma and all the digits after it truncating the number when tolocatstring is used to fill the field. The new issue can be seen above from Mr. Demming which has to do with other issues. While we can get farther along he found that there is a point where negative digits are ignored and I've found some other issues. He suggested that I read a web page describing this problem but it's not clear that I can make it work as it is. I may have to write code that does not use tolocalstring and do brute force slicing and dicing to put the commas in the right place. I will look at his information and see what I have to do.

                      J Offline
                      J Offline
                      jschell
                      wrote on last edited by
                      #10

                      fig0000 wrote:

                      While we can get farther along he found that there is a point where negative digits are ignored and I've found some other issues.

                      Keeping in mind that that is not a 'javascript' issue but rather a computer issue. Most languages, for performance reasons, have limits on the support for native numeric values. All numeric values. The posted article explains the specifics for javascript but that is going to apply to other languages with some variation. As noted there is a specific solution BigInt. That is slower, probably significantly, in general numeric processing and there will also be other issues such as storing it, for example to a database. Other languages will likely also have a solution like that and they will have the same limitations.

                      F 1 Reply Last reply
                      0
                      • J jschell

                        fig0000 wrote:

                        While we can get farther along he found that there is a point where negative digits are ignored and I've found some other issues.

                        Keeping in mind that that is not a 'javascript' issue but rather a computer issue. Most languages, for performance reasons, have limits on the support for native numeric values. All numeric values. The posted article explains the specifics for javascript but that is going to apply to other languages with some variation. As noted there is a specific solution BigInt. That is slower, probably significantly, in general numeric processing and there will also be other issues such as storing it, for example to a database. Other languages will likely also have a solution like that and they will have the same limitations.

                        F Offline
                        F Offline
                        fig0000
                        wrote on last edited by
                        #11

                        In the end it DID turn out to be a JavaScript issue. Last week someone pointed out that I was using replace instead of replace all which I missed not knowing much JaxaScript. This caused only the first comma to be replaced by a blank and second comma was left as a comma. When that string was put into tolocalestring there was a comma left and to locale string received at least one comma which made it fail. Once I used replaceall everything worked fine and I was able to type up to 12 digits with commas inserted correctly.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups