• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2181
  • Last Modified:

Limit a float value to two decimal places Before it is changed to a string and called by an asp:literal

I am new to C#, so I need to limit a string or float to one decimal places...

 float grossYearly = System.Convert.ToSingle(txtField1.Text.ToString());      
float newGross = grossYearly/12;      
float monthly = System.Convert.ToSingle(txtField2.Text.ToString());                
float total = monthly / newGross;              
float newTotal = total*100;                  
string i = newTotal.ToString();
                        Panel2.Visible = false;
                        Panel1.Visible = true;
 Literal1.Text=i;


then it is called here...
<asp:Literal id="Literal1" runat="server"></asp:Literal>%

I know there is a simple answer, but there are a lot of issues with testing here, so I need to be sure...Thanks.
0
theclassic
Asked:
theclassic
  • 3
  • 2
1 Solution
 
theclassicAuthor Commented:
Sorry, I misprinted the title, it should read one decimal place....
0
 
Joel CoehoornDirector of Information TechnologyCommented:
Use a format string.

2 decimal places:
string i = newTotal.ToString("F2");

1decimal place:
strign = i newTotal.ToString("F1");

Standard format strings:
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Custom format strings:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
0
 
prairiedogCommented:
Do you care if the number is rounded up?
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
theclassicAuthor Commented:
It just needs to be rounded, as in 1.35 would be 1.4....
0
 
prairiedogCommented:
Do this then:
string i = newTotal.ToString("0.0");
0
 
theclassicAuthor Commented:
Thank you so much !
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now