Float values in ListBox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ana Casablanka
    New Member
    • Feb 2012
    • 1

    Float values in ListBox

    a have several float values that i want the program to write them in Listbox. how can i limit them to 2 decimals???
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Have a look here... http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

    The ToString method takes a format specifier string that you can use. The characters you're likely interested in are '#' and '0'. With the former, it will tell you to keep that many digits. With the latter, you will keep that many digits and if they don't exist, a zero will be written instead.

    Example...
    Code:
                Console.WriteLine(Math.PI.ToString());
                Console.WriteLine(Math.PI.ToString("#.####"));
                Console.WriteLine(Math.PI.ToString("000.0000"));
    Output:
    3.1415926535897 9
    3.1416
    003.1416
    Alternatively, you can use the Math.Round function to actually round the number to the number of decimal places you wish, then call ToString on the result.

    Code:
                Console.WriteLine(Math.PI.ToString());
                Console.WriteLine(Math.Round(Math.PI, 2).ToString());
    Output:
    3.1415926535897 9
    3.14

    Comment

    Working...