Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New Coder
    Join Date
    Apr 2008
    Posts
    11
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Number Formatting (input and output)

    I am new to Javascript and have a really simple script that I have wrote that allows users to answer two separate questions and then hit a calculate button and it some some simple math.

    That part is working, a working example is here Calculate Example
    and the code is :
    Code:
    <html>
    <head>
    <script type="text/javascript">
    
    	function Calculate() {
    		var amount = parseInt(document.getElementById('amount').value);
    		var customers = parseInt(document.getElementById('customers').value);
    		var monthly = amount * customers;
    		document.getElementById('monthly').textContent = monthly;
    		document.getElementById('monthly').innerText = monthly;
    
    		document.getElementById('yearly').textContent = 12 * monthly;
    		document.getElementById('yearly').innerText = 12 * monthly;
    		return false;
    	}
    
    </script>
    </head>
    <body>
    <form method="post" action="" onsubmit="return Calculate();">
    Enter the amount of your average customer transaction: <input type="text" id="amount" name="amount" /><br />
    Enter the number of new customers per week you could get: <input type="text" id="customers" name="customers" /><br />
    <input type="submit" name="submit" value="Calculate" /><br />
    Additional monthly revenue: $<span id="monthly"></span><br />
    Additional yearly revenue: $<span id="yearly"></span><br />
    </form>
    </body>
    </html>
    The problem I have now is that when someone puts a comma in the input box it ignores everything after the comma and if someone puts in a decimal number it rounds it up instead of using the decimal in the calculations for the output.

    I found online a script for formatting numbers in commas and this is it:
    Code:
    function addCommas(nStr)
    {
    	nStr += '';
    	x = nStr.split('.');
    	x1 = x[0];
    	x2 = x.length > 1 ? '.' + x[1] : '';
    	var rgx = /(\d+)(\d{3})/;
    	while (rgx.test(x1)) {
    		x1 = x1.replace(rgx, '$1' + ',' + '$2');
    	}
    	return x1 + x2;
    }
    Could someone help me out and explain to me how to use the formatting function to format the output with commas and allow commas to be used for the input as well; as well as how to get it to do proper math with the decimal and not ignore it?

    Appreciate any help here.

  • #2
    Regular Coder
    Join Date
    Feb 2009
    Location
    Wheeling, IL
    Posts
    358
    Thanks
    5
    Thanked 62 Times in 60 Posts
    Well, the problem you have comes from:

    Code:
    var amount = parseInt(document.getElementById('amount').value);
    Not sure if you are aware, but an Integer is a number without a decimal. The other type would be 'string', hence the whole issue you're facing with numbers getting cut off. As to formatting it with a comma, you'd want to do that after getting the final result, and you'd definitely want to reformat the string to have a decimal point instead, else your multiplying will not work. And it's actually pretty simple... like so:

    Code:
    amount = amount.replace(",", ".");
    And the same thing for customers.

    Of course, using strings directly might mean that someone will be clever enough to put more than one decimal point in there, but working out a script to handle that... will be a bit of an issue, considering you're not sure which decimal is the right one, so... really not much of a way to take care of that.

    Reformatting afterwards.... shouldn't be too hard either even without the overly complex function you seem to have there. Just use replace again... unless you want specific handling there.
    The way to success is to assume that there are no impossible things. After all, if you think something is impossible, you will not even try to do it.

    How to ask smart questions?

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    For the commas, just strip them out of the .value before calling parseFloat.

    And, by the way, if you want to allow decimal points then of course you can't call parseInt. That function name *means* what it says: It parses an *INTEGER*. Integers don't have an fractional parts. parseFloat parses a floating point number.

    Personally, I'd just strip out *ALL* characters from the user input except digits, period, and minus sign. So (one example, others essentially same):
    Code:
    var amount = parseFloat(document.getElementById('amount').value.replace(/[^\d\.\-]/g,"");
    The .replace method uses a regular expression, and that one says "all characters (the /g on end means "global" or "all") that are NOT (the ^ characters) a digit (\d) or period or minus sign get replaced with blank string."

    Okay?

    Regarding the comma *output*:
    Code:
    document.getElementById('monthly').innerHTML = addCommas( monthly.toFixed(2) );
    You should prefer innerHTML over those other two properties, which don't work in all browsers.

    Now, figure out what's wrong with your math, compared to what your text says.

  • Users who have thanked Old Pedant for this post:

    Eldarrion (05-28-2009)

  • #4
    Regular Coder
    Join Date
    Feb 2009
    Location
    Wheeling, IL
    Posts
    358
    Thanks
    5
    Thanked 62 Times in 60 Posts
    *bangs head against a wall* And figures I'd forget parseFloat() Nice one, Pedant.
    The way to success is to assume that there are no impossible things. After all, if you think something is impossible, you will not even try to do it.

    How to ask smart questions?

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    You like my last sentence, Eldarrion? You see his bug?

  • #6
    Regular Coder
    Join Date
    Feb 2009
    Location
    Wheeling, IL
    Posts
    358
    Thanks
    5
    Thanked 62 Times in 60 Posts
    Most certainly do... average customers per week multiplied by the average amount a customer pays does not equal a monthly average.

    Additionally, while looking through your code, I noticed that you're formatting the numbers with decimals anyway... so after the whole math is done, it's actually pretty easy to replace a decimal with a comma using a straight replace function rather than the function he has for it that does a ton of unnecessary actions. Just something to simplify your solution.
    The way to success is to assume that there are no impossible things. After all, if you think something is impossible, you will not even try to do it.

    How to ask smart questions?

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,103
    Thanks
    80
    Thanked 4,554 Times in 4,518 Posts
    Agree that the comma stuff can be much simpler, but he asked how to use that function, so...

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,444
    Thanks
    11
    Thanked 598 Times in 578 Posts
    no need to re-invent the wheel, it's built into javascript:



    example:
    Code:
    var n = 43534534534.430;
    alert( n.toLocaleString() ) // == "43,534,534,534.43"
    
    //to limit decimals AND add commas, you must use an extra Number casting:
    var n = 43534534534.43034543;
    alert( Number(n.toFixed(2)).toLocaleString() ) // == "43,534,534,534.43"
    your code would be:
    Code:
    var amount = Number(Number(document.getElementById('amount').value).toFixed(2)).toLocaleString();
    this has the benefit of using the proper grouping format that the user expects (, or .), and avoids slower constructs like loops and RegExps...
    Last edited by rnd me; 05-29-2009 at 10:54 AM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%


  •  

    Posting Permissions

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