Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decimal.parse("value") seems odd

Tags:

c#

I am working on someone else's code, and see things like:

if ((somevariable) >  decimal.Parse("24,999.99")) ...

and

return int.Parse("0");

I cannot think of any logical reason to do this instead of

if ((somevariable) > 24999.99) ...

or

return 0;

What am I missing?

like image 890
Outside the Box Developer Avatar asked Dec 07 '22 15:12

Outside the Box Developer


2 Answers

There is a semantic difference between the original code and your proposed change, but you're right in being skeptical.

The conversion from a string is just plain stupid, sorry. There is no need to do that, ever. The difference is that the original code parses the string as a decimal, but your change would use a double. So, it should be:

if (somevariable > 24999.99m) ...
like image 123
Ed S. Avatar answered Dec 09 '22 03:12

Ed S.


For one thing, because 24999.99 is a double value rather than a decimal value - you would want to use 24999.99m. But yes, otherwise it would be a much better idea to use the literal. (I wouldn't bother with the parentheses round the variable, either.)

Note that the code performing parsing will even fail if it's run in some cultures, where the decimal separator isn't . and/or the thousands separator isn't ,. I can't think of any good reason for using this.

like image 38
Jon Skeet Avatar answered Dec 09 '22 03:12

Jon Skeet