View Full Version : Number Formatting (input and output)

05-28-2009, 03:47 AM
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 (www.omgmod.com/calculate.html)
and the code is :

<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;

<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 />

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:

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.

05-28-2009, 06:46 AM
Well, the problem you have comes from:

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:

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.

Old Pedant
05-28-2009, 06:46 AM
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):

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."


Regarding the comma *output*:

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.

05-28-2009, 06:50 AM
*bangs head against a wall* And figures I'd forget parseFloat() Nice one, Pedant.

Old Pedant
05-28-2009, 09:40 AM
You like my last sentence, Eldarrion? You see his bug?

05-28-2009, 07:46 PM
Most certainly do... average customers per week multiplied by the average amount a customer pays does not equal a monthly average. :D

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.

Old Pedant
05-28-2009, 10:28 PM
Agree that the comma stuff can be much simpler, but he asked how to use that function, so...

rnd me
05-29-2009, 10:32 AM
no need to re-invent the wheel, it's built into javascript:


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:

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...