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

产量:47.9 %

我应该将什么传递给 ToString() 以删除输出的百分比符号,如下所示:

47.9

编辑。我应该提到我正在将掩码传递给与它相关的第 3 方组件。不幸的是,我不能用这些数字表演任何杂技。它必须是起到作用的面具。

4

4 回答 4

11

我应该提到我正在将掩码传递给与它相关的第 3 方组件。不幸的是,我不能用这些数字表演任何杂技。它必须是起到作用的面具。

所以我假设你被困住了Float.ToString(String),你不能只编辑p1in f.ToString("p1")。现在这是一个棘手的问题。如果您不害怕破坏与隐含更改相关的任何内容,则可以执行以下操作:

MSDN上记录的“P”数字格式用于NumericFormatInfo.PercentSymbol编写“%”符号。NumericFormatInfo是您当前的成员CultureInfo。您可以做的是克隆您的CurrentCulture,并将 PercentSymbol 修改为""如下所示:

    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());

        }
    }

如果您不想更改 ToString 调用,这将是可行的方法。

于 2010-01-16T03:21:22.790 回答
5
Console.WriteLine((f * 100).ToString("0.0"));
于 2010-01-16T01:29:28.353 回答
2

可以试试

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

或者,如果您不想要空间,请使用Replace('%','\0')

编辑:如果您只能使用该ToString()方法,您可以创建一个NumberFormatInfo对象,将百分比符号设置为空白并将其传递给该方法。(NumberFormatInfoSystem.Globalization命名空间中)例如

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

    float f = 0.479f;

    Console.WriteLine(f.ToString("p1",myNewFormat));
于 2010-01-16T01:29:17.497 回答
2

只有以下怎么样?

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

例如 f = 0.4792 --> "47.9"

MSDN上提供了标准数字格式的列表和说明,以防万一。

于 2010-01-16T01:31:47.880 回答