Friday, February 24, 2012

limit the number of digits after decimal point in flaot data type

Hi..

I have a column in the data base with the type Float,

I want to limit the number of digits after decimal point to 2 when I display the value in ASP.NET but I don't know how!?

the number that appear after calculation llike "93.333333"

I use decimal(2,2) as data type but an error accour and this is the message

"- Unable to modify table.
Arithmetic overflow error converting float to data type numeric.
The statement has been terminated."

Can you help me..

thanks

Hi..


Before saving to database you can use String.Format() method to modify your float value.

First you need to convert float into string using

String myStr = Convert.ToString(yourFloatHere);

And then use String.Format("{0:N}", myStr);

and then again convert it into float using COnvert.ToDouble(MyStr);

Cheers n Hope it would help

|||

Hi..

I try what you suggest but the following error produced:

Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)

Do you konw its solution?!

This is my code:

//------------------

float temp;

String value;

SqlConnection con =newSqlConnection(@."Data Source=localhost ;Initial Catalog=university ;Integrated Security=True");

con.Open();

SqlCommand cmd =newSqlCommand("select SUM(FinalGrid)/COUNT(FinalGrid)from studentSections Where studentSection_UserID='" + Session["ID"].ToString() +"'", con);

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())

{

value =Convert.ToString(reader[0]);

}

String.Format("{0:2}", value);temp =Convert.ToDouble(value); //Here is the error

reader.Close();

//------------------------

Is it has any wrong?!

|||

Do not use the decimal(2,2). Just have the way it is now and just modify the SQL statment that you use to retrive the data and include the function

STR(columnname, lenght, number of decimal places)

This function will automatically round the data in this column to number of decimal places u want when the data is returned to ur ASP.NET application.

|||

Hi..

Can you tell me where I should use this function? and what do you mean by "length" ?

|||

Suppose you are using the query "select column1 from table1" to get the data to your applicaiton, where column1 is the one where you want only 2 decimals

u will have to use it as "select str(column1,10,2) as column1 from table1"

this will make sure you have only 2 decimals in the data that is returned, if there are more than 2 , it will round it to 2 decimals.

|||

Thanks so much its work very nice

No comments:

Post a Comment