Click here to Skip to main content
15,885,998 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
I have a text box that is displaying an answer but the rounding is to several decimal places (~10). How can I have this set to 2 decimal places?

string answer = Convert.ToString(potentialEnergy);
     txtAns.Text = answer;


What I have tried:

string answer = Convert.ToString(potentialEnergy);
string answer = String.Format("%.2f", 5);
txtAns.Text = answer;
Posted
Updated 28-Jul-21 23:37pm

Quote:
C#
string answer = String.Format("%.2f", 5);
That's not a valid .NET format string - there are no placeholders in the string, so the result will simply be "%.2f".

Have a read of the documentation:
Composite formatting | Microsoft Docs[^]
Standard numeric format strings | Microsoft Docs[^]
Custom numeric format strings | Microsoft Docs[^]

C#
string answer = string.Format("{0:F2}", potentialEnergy);

// Or preferably:
string answer = potentialEnergy.ToString("F2");
 
Share this answer
 
 
Share this answer
 
Comments
Maciej Los 27-Jul-21 8:15am    
5ed!
TheRealSteveJudge 27-Jul-21 8:23am    
Thank you!

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