5
\$\begingroup\$

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?

\$\endgroup\$
10
\$\begingroup\$

Wouldn't it be simpler to:

  • strip out any '$' and ',' characters;
  • convert to a real number;
  • multiply by 100;
  • take the integer part.

You can probably do that in one line (my Javascript is a bit rusty):

return Math.round(100 * parseFloat(dollarsAndCentsString.replace(/[$,]/g, '')));

Having said that, I think your f('1000') example is probably wrong: my intuition says I should interpret '1000' as dollars, not cents.

\$\endgroup\$
  • \$\begingroup\$ I'll consider your ideas. For what it's worth, the reason that I consider the dollars and cents separately as real numbers is to avoid floating point arithmetic round-off errors. Perhaps they are not relevant in this context. 0.1 + 0.2 = 0.30000000000000004. \$\endgroup\$ – Rice Flour Cookies Jul 20 '11 at 14:14
  • \$\begingroup\$ And you're right f('1000') should be 10000. \$\endgroup\$ – Rice Flour Cookies Jul 20 '11 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.