1

i am working on a problem to round decimal values everything is fine but at one certain point it gives me error input string was not formatted after debugging my code i found 4.90702817E-05 this which gives me error on this calling code . It converts all code but throws exception when it finds above string .

 MarketValue = Convert.ToDecimal(row["MarketValue"].ToString()) ,
Dev
  • 307
  • 1
  • 2
  • 12
  • 2
    `throws exception` - What exception it is throwing? – Anuraj Jun 17 '14 at 09:17
  • possible duplicate of [Parse a Number from Exponential Notation](http://stackoverflow.com/questions/3879463/parse-a-number-from-exponential-notation) – Sean Airey Jun 17 '14 at 09:19
  • What is the real type contained in that `row["MarketValue"]`? To put it differently: do you really need a `.ToString` followed by `Convert` or `Parse`, or would a plain cast work (`(decimal)row[".."]`)? – Hans Kesting Jun 17 '14 at 09:38

4 Answers4

2
  MarketValue = Decimal.Parse(row["MarketValue"].ToString(), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Convert to Decimal by using below code. After getting the Value in Decimal form round it up.

decimal d = Decimal.Parse("4.90702817E-05", System.Globalization.NumberStyles.Float);
Mark
  • 2,380
  • 11
  • 29
  • 49
HomeWork
  • 263
  • 1
  • 4
  • 14
  • as you are getting the number as a scientific notation it is not able to round up directly. So convert that number to the original Decimal number and then you can manipulate as you wish. – HomeWork Jun 17 '14 at 09:24
  • Mark your answer is same which i did MarketValue = decimal.Parse(row["MarketValue"].ToString(), NumberStyles.Float). – Dev Jun 17 '14 at 10:10
  • no there is bit change as compare to your previous answer. just check it clearly.i test that it is working fine. – HomeWork Jun 17 '14 at 10:21
0

The reason for the exception could be that the value is not a valid decimal.

The following code uses a method called TryParse(...). This method returns false if the value is not a valid decimal, rather than throwing an exception.

For example:

decimal d = 0;
if (Decimal.TryParse(row["MarketValue"].ToString(), out d))
{
    MarketValue = d;
}
rhughes
  • 9,257
  • 11
  • 59
  • 87
0

I'd advise you to use TryParse using following NumberStyles

    decimal d = 0;
    if (Decimal.TryParse(row["MarketValue"].ToString(), NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out d))
    {
        MarketValue = d;
    }
Bartosz Wójtowicz
  • 1,321
  • 10
  • 18