I have this JavaScript code to format a number for US dollars that was given many thumbs up on Stackoverflow. It works well in the latest web browsers, but it causes the JavaScript to fail in IE7. I was trying to use a function that didn’t require JQuery because the rest of this project isn’t using it:
function formatDollar(num) {
var p = num.toFixed(2).split(".");
return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
IE7 to the user simply says “Error on Page”. In debugging mode on IE7 is complains it isn’t an expected Object for the form being submitted on the On Click line. If I remove the above function and have it pass the numbers without formatting it works in IE7. It also complains about the line that starts with the first “return”. I have eliminated everything else from the JavaScript and this function is the culprit it appears.
The
reducefunction is only available in JavaScript 1.8 (ECMAScript 5) and above, which IE7 does not implement. If you’re not already using any libraries that provide its functionality cross-browser, it can be implemented thus:Alternatively, if you don’t mind not using the simplified syntax of
reduce, just replace it in your function with an equivalent loop (e.g. thewhileloop above, or aforvarient).Reference