HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptModerate

Code to Parse dollars and cents?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
centsandparsedollarscode

Problem

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 '

Anyone care to critique my code? glyph, if it was passed in. if (dollarsAndCentsString.split('

Anyone care to critique my code?).length == 2) dollarsAndCentsString = dollarsAndCentsString.split('

Anyone care to critique my code?)[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?

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#3527, answer score: 10

Revisions (0)

No revisions yet.