开发者

How can I format a value as a percentage without the percent sign?

float f = 0.479f;
Console.WriteLine(f.ToString("p1"));

The output: 47.9 %

What should I pass to ToString() in order to remove the percentage sign for output like this:

47.9

开发者_高级运维

EDIT. I should have mentioned that I am passing the mask to a 3rd party component that does it's thing with it. I can't perform any acrobatics with the numbers unfortunately. It has to be the mask that does the trick.


I should have mentioned that I am passing the mask to a 3rd party component that does it's thing with it. I can't perform any acrobatics with the numbers unfortunately. It has to be the mask that does the trick.

So I assume that you are stuck with Float.ToString(String), and that you cant only edit the p1 in f.ToString("p1"). Now that's a tricky one. If you're not afraid of breaking anything related to the changes implied, you could do the following:

The "P" numeric format, as documented On MSDN, uses NumericFormatInfo.PercentSymbol in order to write the "%" sign. NumericFormatInfo is a member of your current CultureInfo. What you could do, is clone your CurrentCulture, and modify the PercentSymbol to "" like the following:

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            float f = 0.479f;
            Console.WriteLine(f.ToString("p1")); //will write 47.9%

            CultureInfo ci = CultureInfo.CurrentCulture.Clone() as CultureInfo;
            ci.NumberFormat.PercentSymbol = "";            

            System.Threading.Thread.CurrentThread.CurrentCulture = ci;
            Console.WriteLine(f.ToString("p1")); //will write 47.9

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

        }
    }

This would be the way to go if you don't want to alter the ToString call.


Console.WriteLine((f * 100).ToString("0.0"));


How about just the following?

Console.WriteLine((f * 100).ToString("F1"));

e.g. f = 0.4792 --> "47.9"

A list and descriptions of standard numeric format are available here on MSDN, in case it helps.


Could try

Console.WriteLine(f.ToString("p1").Replace('%',' '));

Or, if you want don't want a space, use Replace('%','\0')

EDIT: If you can only use the ToString() method, you could create a NumberFormatInfo object, set the percentage symbol to be blank and pass it into the method. (NumberFormatInfo is in the System.Globalization namespace) e.g.

    NumberFormatInfo myNewFormat = new NumberFormatInfo();
    myNewFormat.PercentSymbol = "";

    float f = 0.479f;

    Console.WriteLine(f.ToString("p1",myNewFormat));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜