Click here to Skip to main content
15,921,905 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
i am using asp.net 4.0

how can i decrement the float variable up to 2 place after decimal

i.e.
34.6789878 to 34.678
Posted

Use Math.Round[^]


"float m1 = Convert.ToInt32(TextBox11.Text);
float m2 = Convert.ToInt32(TextBox12.Text);
float m3 = (m1 / m2) * 100;

then where i use math.round....??"


Why are you converting to floats, using ToInt32?

Use this instead:
C#
float m1 = Convert.ToSingle(TextBox11.Text);
float m2 = Convert.ToSingle(TextBox12.Text);
float m3 = (float) Math.Round((m1 / m2) * 100, 3);
Or better use TryParse to convert them, as you could then report a user error if he enters "Hello" instead of "123.45".
In addition, you should check your inputs: if the user puts "0" in TextBox12, then the code will throw a Divide by Zero exception.

BTW:
1) Deleting your question when it has been replied to is very rude, and can make people unwilling to help you again.
2) Please don't use the default names that VS supplies: change them to something more meaningful. You may understand what is supposed to be in "TextBox7" today, but next week it may be a blur. Calling it "inputUserName" or whatever makes your code more readable, and easier to maintain.
3) I really meant it about Parameters.Add being depreciated in favour of Parameters.AddWithValue.
 
Share this answer
 
v3
Comments
Shagun Bansal 6-Mar-11 7:51am    
float m1 = Convert.ToInt32(TextBox11.Text);
float m2 = Convert.ToInt32(TextBox12.Text);
float m3 = (m1 / m2) * 100;

then where i use math.round....??
OriginalGriff 6-Mar-11 8:03am    
Answer updated
Sergey Alexandrovich Kryukov 6-Mar-11 13:44pm    
Griff, I really doubt OP needs rounding in fact, please see my Answer.
--SA
I doubt you really need rounding. This is rarely needed. I suspect you simply need to obtain string presentation will less digits.

For this purpose, use proper format:
C#
float value = 34.6789878;
//...
string number = value.ToString("F3");
string fortmatted = string.Format("Formatted value: {0:F3}", value);


—SA
 
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