Solved

How do I round numbers in C# in a text box?

Posted on 2004-10-18
13
2,355 Views
Last Modified: 2008-01-09
I am currently building a Web Page in Visual Studio.NET.... (C#).  I am trying to figure out how to 'round numbers" that I am pulling into text boxes in my Web Form from a DB.  Currently, When I view the page the numbers are coming up as "0.96544456754363."  I want to round them to  "0.97". How would I do this in C#?
Thanks
PLEASE HELP... I know there is probably an easy way to do this,....
0
Comment
Question by:bripena
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
  • +3
13 Comments
 
LVL 9

Accepted Solution

by:
msdixon earned 250 total points
ID: 12340317
assuming it's a decimal object...


decimal val = 0.96544456754363;

val.ToString("n2"); // this tells it to display a number with two trailing decimal points. i.e. 28.1038 will display as 28.10
0
 

Author Comment

by:bripena
ID: 12340358
now- being I am pulling from a DB and these numbers are displayed in text boxes- can I use the decimal val to account for any value that would appear there- in other words- I don't want to key in every value- so what can I use to account for all vlaues that would be pulled into that text box???
0
 
LVL 3

Expert Comment

by:aacool
ID: 12340515
You would need to check the text and validate whether it is a number(float) or whether it is text. IF you got text from the db, perhaps you could put NaN (Not a number) as text.

So you could validate the text using a parser to check for only numbers(float) and then round those off to 2 digits as shown.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:bripena
ID: 12341231
the number os a float.....
0
 

Author Comment

by:bripena
ID: 12341247
if I integrate the following....
                   double x;

                  x = textBoxValue;

                  double roundX = System.Math.Round(x,2);

The problem is - it is not recognizing 'textboxvalue' and I have multiple text boxes in which this needs to apply to.....
any thoughts???
0
 
LVL 9

Expert Comment

by:s_sansanwal
ID: 12343107
what is textBoxValue?

Have you declared it anywhere?

Cheers,
S Sansanwal
www.sansanwal.com
0
 
LVL 3

Expert Comment

by:aacool
ID: 12343720
this is cryptic code.

Taking a shot,

assume
string textboxvalue = Textbox1.Text

if(isString(textboxvalue)==false) // check if string
{
     double x = double.Parse(textboxvalue);
    double roundX = System.Math.Round(x,2);
    // do something
}

What exactly is the code and what is the error?
0
 
LVL 18

Expert Comment

by:armoghan
ID: 12344554
Make a custom textbox component by extending from textbox named numerictextbox and override the Text property. use the above methods to set and get as rounded number
0
 
LVL 3

Expert Comment

by:Realmrat
ID: 12345126
String.Format("{0:F2}", 0.96544456754363);          =  .97

double varName = 0.96544456754363D;

String.Format("{0:F2}", varName);                         =  .97

This will round to the nearest fixed(F) decimal point (2).


String.Format("{0:c}", varName);                           =  $0.97

Displays the number in currency.


Check out this link for a list of all the formating options.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconstandardnumericformatstrings.asp


 - Joe
0
 
LVL 3

Expert Comment

by:Realmrat
ID: 12345148
Here's an ASP.NET Implimentaion that I've used:

                                                                 Page.aspx
--------------------------------------------------------------------------------------------------------------------------------------

<asp:DataList id="DataList1" runat="server" Width="100%">
<ItemTemplate>
     <asp:Label id=ItemPriceDataListLabel Text="<%# DataItemPrice(Container.DataItem) %>" Runat="server">
     </asp:Label>
</ItemTemplate>
</asp:DataList>


                                                                Code Behind
--------------------------------------------------------------------------------------------------------------------------------------

        protected string DataItemPrice(object DataItem)
        {
            DataRowView row = (DataRowView) DataItem;
            return String.Format( "{0:c}", row["UnitCost"]);
        }


This is using Databinding on the DataList.

 - Joe
0
 

Author Comment

by:bripena
ID: 12347169
I tried aacool's method but received the below error- any one know what is wrong????

string textboxvalue=txtclinicaltotal.Text;
                  if(IsString(textboxvalue)==false)
                  {
                        double x = double.Parse(textboxvalue);
                        double roundX = System.Math.Round(x,2);
                        // do something
                  }

c:\inetpub\wwwroot\CREAMPROFILE1\CREAMFORM.aspx.cs(108): The name 'IsString' does not exist in the class or namespace 'CREAM1.WebForm1'
0
 
LVL 3

Expert Comment

by:aacool
ID: 12352188
isString is a helper function - you need to implement it to check whether the value is a string. One impl is:

            public static bool isString(string txt)
            {
                  bool isStr = false;
                  char[] chr = txt.ToCharArray();
                  foreach(char ch in chr)
                  {
                        if(Char.IsLetter(ch)==true)
                              isStr = true;
                  }
                  return isStr;
            }
0
 
LVL 3

Expert Comment

by:aacool
ID: 12377107
Did you get what you wanted working?
0

Featured Post

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question