Home > front end >  Avoid decimal.TryParse throwing OverflowException
Avoid decimal.TryParse throwing OverflowException

Time:03-17

I have a quantity field and a price field, which are both decimals. It's possible to order huge quantities and also extremely expensive stuff. The combination of both never happens in real life but that doesn't mean that a user might enter both an enormous quantity and price.

To make sure that I won't end up with a too big number in the "Total" field I'm trying to do a decimal.TryParse() but I get an OverflowException when multiplying the vales. Does anyone have any smart idea how to avoid this?

decimal outvalue;
decimal qty = 10000000000000000;
decimal price = 10000000000000000;

if (!decimal.TryParse((qty * price).ToString(), out outvalue))
{
    ModelState.AddModelError("myfield", "Total value is too big");
}

Throws:

OverflowException

CodePudding user response:

What don't just cast both decimals to double, multiply them and, finally, check?

  //TODO: put any reasonable value instead of 1e20 
  if ((double) qty * (double) price > 1e20) {
    ModelState.AddModelError("myfield", "Total value is too big");
  } 

CodePudding user response:

Straightforward way, as @Crowcoder said, handle the overflow exception and prompt user if needed

Other way:

if (decimal.MaxValue / qty < price)
... sorry, wrong input

(not tested...)

CodePudding user response:

First, let's understand the problem with your code: The exception is raised before the TryParse is executed. If we expand your code in a fewer instructions per line, you get:

decimal outvalue;
decimal qty = 10000000000000000;
decimal price = 10000000000000000;
decimal total = qty * price;  // Exception raised here
string temp = total.ToString();

if (!decimal.TryParse(temp, out outvalue))
{
    ModelState.AddModelError("myfield", "Total value is too big");
}

To fix your code, you have some options, I recomend you see BigInterger. You can also see about checked and unchecked arithmetic contexts.

CodePudding user response:

In addition to other answers, I would suggest using some reasonable limits on both price and quantity. Google suggest the most expensive item is around 10^10 USD, 6 magnitudes lower than in your example. likewise, ordering more than say 10^12 of anything would be unlikely, very large quantities would probably be ordered in bulk, by weight.

The range of decimal is 10^28, so as long as your count and price are both lower than 10^13 you should be fine.

  • Related