Sora
Sora

Reputation: 2551

Convert.ToInt64 fails when value is "0.00000"

5 my code is like this

protected long Getvalue()
{
   DataTable dt = GetDataBaseValue();
     if (dt.Rows.Count > 0)
     {
      return Convert.ToInt64(dt.Rows[0]["BALANCE"].ToString());
     }
    return 0;
}

dt.Rows[0]["BALANCE"].ToString()=0.00000 I am getting the error here

PS: I tried to do this return long.Parse(...) and I got the same error

Upvotes: 2

Views: 3913

Answers (3)

Yaser Jaradeh
Yaser Jaradeh

Reputation: 322

Use Decimal.Parse("0.0000"); this is used for currency Not Long or Int64

Upvotes: 1

user2864740
user2864740

Reputation: 61935

The problem is that "0.00000" is a String, which is an invalid format for "parsing to a long"1.

However, it may be sufficient to omit the ToString() conversion, and thus the above error, depending on what type the database actually returns. If the database returns an appropriate double/float/decimal then the following "Will Work", even if losing precision.

// Source is a double
Convert.ToInt64(0.0d)             // -> 0
Convert.ToInt64(0.5d)             // -> 0 (half-even rounding)
Convert.ToInt64(1.5d)             // -> 2 (half-even rounding)
Convert.ToInt64(double.MaxValue)  // -> OverflowException

// Source is a string
Convert.ToInt64("0")    // -> 0
Convert.ToInt64("0.0")  // -> FormatException: "not in a correct format"

If, for some uncorrectable reason, the database returns a String in the given format, it should suffice to first convert the string to a double/decimal (which do support such a format) and then to a long. Similar overflow and loss of precision cases are possible.

long v = (long)Convert.ToDecimal(dt.Rows[0]["BALANCE"]);

By default, .NET will parse integer values (e.g. int, long) from strings only when they conform to the pattern \s*[-+]?\d+\s* and will throw a FormatException otherwise; this is discussed in more detail in the linked documentation.

Upvotes: 6

lc.
lc.

Reputation: 116528

0.00000 is not a valid value for Int64. Perhaps you intended to use a Decimal (it looks like a currency amount) or otherwise truncate/round the value first?

Upvotes: 6

Related Questions