isita
isita

Reputation: 53

how to format data

I am getting the following values from database:

99, 12, 12.2222, 54.98, 56, 17.556

Now I want to show that values like below: 99%, 12%, 12.22% , 54.98% , 56%, 17.55%

Please give me any suggestion to acchive this.

Upvotes: 3

Views: 170

Answers (5)

Syeda
Syeda

Reputation: 1205

Try this Out

        List<double> myList = new List<double>();
        myList.Add(0.1234);
        myList.Add(99);
        myList.Add(12.1234);
        myList.Add(54.98);
        foreach (double d in myList)
        {
            string First = string.Format("{0:0.00%}", d); //Multiply value by 100
            Console.WriteLine(First);                    
            string Second = string.Format("{0:P}", d);//Multiply value by 100
            Console.WriteLine(Second);  
            string Third = string.Format("{0:P}%", d.ToString());//Use this One 
            Console.WriteLine(Third);  
            string Four = d.ToString() + "%"; //Not a good idea but works
            Console.WriteLine(Four);
            Console.WriteLine("=====================");  
        }

        Console.ReadLine();

I have made a little trick here {0:P} will multiply your given value by 100 and then show it but you just want to place a % sign after value so first convert the given value to TOString than apply {0:p}

Upvotes: 1

BellBat
BellBat

Reputation: 145

Use the ToString method that takes a string format - the format you want is "P2" or the custom format #0.##%. Both of these formatting options multiply by 100, expecting your data to be in standard percent format so you will need to divide to accomadate and use it.

To use ToString without the divide you can use "#0.##\%" which will format the numeric part and include the percent sign as a literl, this is the equivilent for ToString as the format from Anton Semenov's answer using the string.Format function on this thread.

Msdn article - Standard Formats
Msdn article - Custom Formats

Upvotes: 2

The Mask
The Mask

Reputation: 17427

to formart 12.2222 use f

 string.Format("{0:f}%", 12.2222); //output 12,22% 

Upvotes: 1

Anton Semenov
Anton Semenov

Reputation: 6347

Its very easy in C#:

[EDIT]

var val = 99.569;
string result = string.Format("{0:0.##}%", val);

You can take a look for Format method of string class:
http://msdn.microsoft.com/en-us/library/fht0f5be.aspx

and I recomend you to take a look on custom format strings:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Upvotes: 4

Kjartan
Kjartan

Reputation: 19111

If you want to specify the number of decimal places to 2 (ie. not 12.2222%, but 12.22%), then use:

val.ToString("0.00") + "%"

Note that this will round the number off, so 12.226 would be shown as 12.23%, etc.

Upvotes: 0

Related Questions