I've written code to parse dollars and cents entered by the user. The value returned is the total number of cents.
For example:
f('$1.50') = 150
f('1.5') = 150
f('0') = 0
f('1000') = 1000
f('$12,500.00') = 12500000
functions.GetTotalCents = function (dollarsAndCentsString) {
// Cast the value passed in to a string in case a number was passed in.
dollarsAndCentsString = dollarsAndCentsString.toString();
// First, discard the '$' glyph, if it was passed in.
if (dollarsAndCentsString.split('$').length == 2)
dollarsAndCentsString = dollarsAndCentsString.split('$')[1];
// If the user delimmited the groups of digits with commas, remove them.
dollarsAndCentsString = dollarsAndCentsString.replace(/,/g, '');
// Next, divide the resulting string in to dollars and cents.
var hasDecimal = (dollarsAndCentsString.split('.')).length == 2;
var dollarsString, centsString;
dollarsString = dollarsAndCentsString.split('.')[0];
var centsString = hasDecimal ? dollarsAndCentsString.split('.')[1] : '0';
var dollars = parseInt(dollarsString, 10);
var cents;
if (centsString.length == 1)
cents = parseInt(centsString, 10) * 10;
else cents = parseInt(centsString, 10);
if (cents > 99 || isNaN(cents) || isNaN(dollars) || !isFinite(dollars) || !isFinite(cents))
return 0;
var totalCents = dollars * 100 + cents;
return totalCents;
};
Anyone care to critique my code?