SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Wishful Thinking webmasternovis's Avatar
    Join Date
    Jul 2002
    Location
    England
    Posts
    430
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Commas In Input Boxes

    Hi all,

    I've got a script that adds input boxes and puts the result in a seperate box. My first problem was getting NaN errors, although I stopped this through this code:

    PHP Code:
    function toNum(input) {
            if (
    input) {
         return 
    parseFloat(input.replace(/[^0-9.-]/g,"10"));
            }
            return 
    0
    My next issue is with commas. When somebody inserts commas the result box comes up with totally the wrong result. Does anyone know a way to "ignore" the commas entered in the text boxes?

    Thanks a lot,
    Mike

  2. #2
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    input = input.replace(/,/g, "");
    Birnam wood is come to Dunsinane

  3. #3
    Wishful Thinking webmasternovis's Avatar
    Join Date
    Jul 2002
    Location
    England
    Posts
    430
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for that, it partly solves my problem. Would you be able to say how the comma can be ignored, but the numbers after it still counting towards the final result?

    For example, if you type "3,000" it will just class it as 3 at the moment. Is there anyway it could take the comma out, and therefore class it as 3000?

    Also, I didn't realise the thread was posted twice. On the first time it timed out so I presumed it wasn't posted.

    Thanks

  4. #4
    SitePoint Author silver trophybronze trophy

    Join Date
    Nov 2004
    Location
    Ankh-Morpork
    Posts
    12,159
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you include the line I posted before your return statement, commas will be ignored.

    Your code looks a bit odd. If you just want to ignore all non-numeric characters, try
    Code:
    function toNum(input) {
        if (input) {
            return parseFloat(input.replace(/[^0-9.-]/g, ""));
        }
        return 0;
    }
    Birnam wood is come to Dunsinane


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •