Asil Eris
Asil Eris

Reputation: 31

when casting from a number the value must be a number less than infinity

I just want to round the value which comes from datatable,Data comes from SQL to datable.Also datatable have null values i guess this the problem but please also you check for me

string Maxmonthlytable = Math.Round((decimal)monthlytable.Rows[u][3], 2, MidpointRounding.AwayFromZero).ToString();

I get the error " when casting from a number the value must be a number less than infinity "

Upvotes: 0

Views: 5885

Answers (3)

Instead of using the cast (decimal) or using the cast (int), you have to use the cast (System.Decimal) or (System.Int32) and that will make this problem go away.

Upvotes: -1

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could use the DataRow.Field method which supports nullables:

decimal? num = monthlytable.Rows[u].Field<decimal?>(3);
Console.Write(num.HasValue 
                 ? Math.Round(num.Value, MidpointRounding.AwayFromZero)
                 : "no value");

Upvotes: 2

Marco
Marco

Reputation: 57583

You could try:

decimal num = 0;
if (monthlytable.Rows[u][3] != DBNull.Value)
    num = Math.Round((decimal)monthlytable.Rows[u][3], 2, MidpointRounding.AwayFromZero)
string Maxmonthlytable = num.ToString();

Upvotes: 0

Related Questions