\$\begingroup\$
\$\endgroup\$
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?
FrustratedWithFormsDesigner
4843 silver badges11 bronze badges
asked Jul 18, 2011 at 20:51
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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.
-
\$\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\$Vivian River– Vivian River2011年07月20日 14:14:14 +00:00Commented Jul 20, 2011 at 14:14
-
\$\begingroup\$ And you're right f('1000') should be 10000. \$\endgroup\$Vivian River– Vivian River2011年07月20日 14:17:44 +00:00Commented Jul 20, 2011 at 14:17
default