So I’ve been writing a new point of sale page for use by our customer service reps in accepting orders by phone. It will be replacing a very old, ugly, slow, and inefficient strictly php/html web application with one which is heavy javascript/ajax/dom, css, html, and php. I noticed when working on a point of sale page for another department months ago that javascript was a pain in the ass when doing math based on values stored inside form fields.
Javascript views everything stored in a form field as a string. Which is very different for me because I’m use to the PHP model where it doesn’t classify variables as strings or integers, it just knows when to do math based on the operator you use. Now there are a few tricks I’ve come up with on my own, and a few I found googling to work around these nuances. I’d love some feedback and additional work-arounds from anyone who reads this though.
Here we go:
Multiply by 1
I’ve been using this one the most lately since it’s so easy. Say we have a number stored in a field called subtotal and we want to get the tax off it, and then use these two fields to come up with a final total. Here’s what we would do:
var subTotal = document.myform.subtotal.value*1; var tax = (document.myform.tax.value*1)*.06; var total = subTotal + tax;
Formatting for currency
function currencyFormatted(amount) { var i = parseFloat(amount); if(isNaN(i)) { i = 0.00; } var minus = ''; if(i '<' 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 100; s = new String(i); if(s.indexOf('.') '<' 0) { s += '.00'; } if(s.indexOf('.') == (s.length - 2)) { s += '0'; } s = minus + s; return s; }
remove the single quotes around the greater than/less than signs.
The other option is using the parseInt function to parse a string as an integer, but I haven’t had that much success. Have you ever had problems getting your javascript to format integers as currency? Here’s a function I found that does it for you:
function currencyFormatted(amount) { var i = parseFloat(amount); if(isNaN(i)) { i = 0.00; } var minus = ''; if(i < 0) { minus = '-'; } i = Math.abs(i); i = parseInt((i + .005) * 100); i = i / 100; s = new String(i); if(s.indexOf('.') < 0) { s += '.00'; } if(s.indexOf('.') == (s.length - 2)) { s += '0'; } s = minus + s; return s; }
In any case what I ended up doing as offloading as much math to my PHP scripts through the use of ajax http requests. I’m not sure what sort of load this creates on apache/php, but it certainly makes development easier.
Related posts:
Tags: currency, math, type caste