Calculations in JavaScript
I just finished creating a “value†calculator for a company using JavaScript. It computed the overall value a person would save by joining the organization – nothing fancy, just a couple of input boxes, some simple equations and 10 values to display. What was tricky, at least for a JavaScript neophyte like me, was getting the numbers in the correct format - both on output and input.
For instance, something as trivial as grabbing the number from an input box and using in a calculation took me some time to figure out. First, I didn’t want to limit what the user could put into the text box. Ie, I wanted to allow “$30,000â€, “30,000†, “30000†or “ 30,000.00†and not force the user to enter some contrived number for the sake of computational ease. After some mucking around, I came up with this:
var cop = document.getElementById(’cop’).value;
//strip out all non-numbers, except a decimal and turn into a float
cop = parseFloat(cop.replace(/[^.0-9]/g,'’));
// if it still isn’t a number (user had nothing in the field), make it 0
cop = isNaN(cop) ? 0 : cop;
I remember when I was very new to JavaScript and programming in general, and didn’t know to use parseFloat and parseInt. If you forget to do that for a value you have pulled from a input box, JavaScript will typically concatenate the value, as it treats it as a string:
Var num = document.getElementById(’cop’).value;
//outputs “65†instead of 11
alert(num + 5);
Next, I had to display the damn thing like this “$30,000.06â€. I started with a regular expression I have used in PHP before: /(?<=d)(?=(?:ddd)+$)/ . But javascript complained about “?<=†which is a positive lookbehind. Apparently, JavaScript doesn’t support it. Digging into my books, I found toLocaleString(), which seemed to meet my criteria. In fact, it works without a problem in Internet Explorer (at least 6.0), but it exhibits some strange behaviors in Firefox. In Firefox, it doesn’t display the “.00†if the number doesn’t already contain it and it will only display one decimal place without the trailing “0â€. It wasn’t a major problem, but an annoyance nonetheless. I tried using toFixed(2) and then toLocaleString(), but it still didn’t work in Firefox and rather than writing extra code, I let it be.
One final note. Using the CSS selector :disabled doesn’t work in Internet Explorer. I wanted to hide input boxes I used to display the numbers and disabled them. But in Internet Explorer, it ignores any “font-color†declarations and outputs grey text, so it will look different than the rest of the text. I just hide the input boxes, and left them as enabled…