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?

asked Jul 18, 2011 at 20:51
\$\endgroup\$

1 Answer 1

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.

answered Jul 18, 2011 at 23:48
\$\endgroup\$
2
  • \$\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\$ Commented Jul 20, 2011 at 14:14
  • \$\begingroup\$ And you're right f('1000') should be 10000. \$\endgroup\$ Commented Jul 20, 2011 at 14:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.