Reputation: 6778
I have a formatting problem with this line:
Decimal amount = Convert.ToDecimal(String.Format("{0:.##}", doubleAmount));
If doubleAmount
is 0.0, it throws a format exception. How do I handle 0.0?
Upvotes: 1
Views: 1633
Reputation: 55419
The problem is that the format string {0:.##}
formats 0 as an empty string, but
an empty string is not a valid argument for Convert.ToDecimal
. To avoid a possible FormatException, you can use {0:0.##}
to format 0 as 0
.
(User sasfrog suggests {0:#.##}
, but since that also formats 0 as an empty string, it doesn't work.)
However, if you're just trying to round a Double value to two decimal places and store the result in a Decimal variable, then you should use
Decimal amount = Decimal.Round((Decimal)doubleAmount, 2, MidpointRounding.AwayFromZero);
and skip the unnecessary overhead of string formatting and parsing.
Upvotes: 6