Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
2.00/5 (8 votes)
See more:
I want to do data format string function for my c# code.
string s = 0.98677;
this value come directlly from database table and catch it in string variable.
I want output only 0.98, then i use data format string.
string str = (s,"0:0.##");
or
string.format("0:0.00",s)
but this not give me exact answer upto 2 digit 0.98.
Please help me for my this problem.

regards,
Ravi
Posted
Updated 1-Jun-11 1:54am
v4
Comments
Sergey Alexandrovich Kryukov 1-Jun-11 15:08pm    
C# or VB.NET?!!! Tag properly.
--SA

Seems like you just want first to decimals, not rounding.
I mean 0.98 for 0.98677, not 0.99. If it is the case, use following function
C#
public string getValueUpto2Decimal(string value)
{
	if (value.Contains(".")) { 
		value += "00"; //to ensure that there are at least 2 digits after decimal point
	} else {
		value += ".00"; //place 00 after decimal
	}
	return value.Substring(0, value.IndexOf(".") + 3);
}


This is purely based on string functions.

Though I seriously have a doubt that you get a string value from database. If you get a double from database, then just use ToString() to pass it to the function.
 
Share this answer
 
Here is one more solution

C#
double   s = 0.93245;
           string s1= s.ToString("0.00");
 
Share this answer
 
I must Suggest you to
Click Here [^]
 
Share this answer
 
decimal d=.....
label1.text=string.format("{0:f2}",d);
 
Share this answer
 
u can use substring or remove method in c#

try this

MIDL
string s = "0.98677";
 s=s.Remove(4);
 
Share this answer
 
Comments
Quirkafleeg 1-Jun-11 6:52am    
...and with a different string of, say "11.98677"?
Try with

string.format("{0:(#).##}",s)


It will work for sure,
 
Share this answer
 
Your data is a string, not a number, so numeric formatting strings will not work. You either need to manipulate it as a string (find the decimal separator and then take two more characters), or use double.Parse to get a number and then format that with a numeric format string.

Numbers should come out of a database as numbers, though. Have you set your database schema correctly?
 
Share this answer
 
try this code
C#
string s = "9.5688";
            double val ;
            if (Double.TryParse(s, out val))
            {
               String.Format("{0:0.00}", Math.Round(val, 2));

            }



output : 9.57
 
Share this answer
 
Comments
Ravi Sharma 2 1-Jun-11 8:42am    
Thanks A lot for giving me perfect solution................
may this Work

double dNum = 0;
           dNum =0.98677;
           string.Format("{0:n4}", dNum); 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900