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

.net-2.0, c#, tostring

Solution

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.

Problem

``` 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.

Original source