1

我有一个 WPF 文本框,用户可以在其中键入数字。现在我正在寻找一种字符串格式,它可以将 TextBox 编号每 3 点分开(如0,0),但我想要用斜杠反斜杠或其他字符分隔文本。而且我们不知道我们的号码有多少点。

我正在搜索字符串格式而不是 Linq 解决方案等。我阅读了Microsoft 帮助,但找不到任何方法。

样本 = 123456789 == > 123/456/789(好)--- 123,456,789(坏)

更新 :

谢谢大家,但我搜索类似stringformat= {}{0:0,0}等的东西。我的意思是不想使用字符串函数,如 regex、replace 或 linq 或任何 c# 代码。我想使用 {#,#} 等字符串。请参阅我帖子中的 microsoft 链接我需要为我的问题创建一个字符串。

4

3 回答 3

2

由于 OP 坚持使用String.Format

string input; //the input of your textbox
int temp = int.Parse(input); //parse your input into an int

//the Format() adds the decimal points, the replace replaces them with the /
string output = String.Format("{0:0,0}", temp).Replace('.', '/');

这里重要的一步是将文本框的文本转换为整数,因为这简化了小数点的插入String.Format()。当然,您必须确保您的文本框在解析时是一个有效数字,否则您可能会遇到异常。


编辑

所以...您有一些动态长度的数字,并希望使用静态格式字符串对其进行格式化(因为正则表达式、字符串替换、ling 或任何 c# 代码(!)都是不行的)?这是不可能的。您必须有一些动态代码在某处创建格式字符串。
在不再次引用正则表达式或字符串替换的情况下,这里有一些代码可以根据您的输入数字创建格式字符串。
这样你就只有一个String.Format()电话。也许您可以将算法放在其他地方创建格式字符串,然后从您需要的任何地方调用它。

string input; //the input of your textbox
int temp = int.Parse(input); //parse your input into an int

string customString = "{0:";
string tempS = "";

for (int i = 0; i < input.Length; i++)
{
    if (i % 3 == 0 && i != 0)
    {
        tempS += "/";
    }

    tempS += "#";
}

tempS = new string(tempS.Reverse().ToArray());

customString += tempS;
customString += "}";

string output = String.Format(customString, temp));
于 2013-10-28T10:44:53.347 回答
2

您可以使用NumberFormatInfo.NumberGroupSeparator 属性

来自 MSDN 的示例

using System;
using System.Globalization;

class NumberFormatInfoSample {

    public static void Main() {

    // Gets a NumberFormatInfo associated with the en-US culture.
    NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;

    // Displays a value with the default separator (",").
    Int64 myInt = 123456789;
    Console.WriteLine( myInt.ToString( "N", nfi ) );

    // Displays the same value with a blank as the separator.
    nfi.NumberGroupSeparator = " ";
    Console.WriteLine( myInt.ToString( "N", nfi ) );

    }
}


/* 
This code produces the following output.

123,456,789.00
123 456 789.00
*/

为您 - 将 NumberGroupSeparator 属性设置为 '/'

更新 另一个样本

var t = long.Parse("123/456/789",NumberStyles.Any, new NumberFormatInfo() { NumberGroupSeparator = "/" });
var output = string.Format(new NumberFormatInfo() { NumberGroupSeparator="/"}, "{0:0,0}", t);
于 2013-10-28T10:02:07.093 回答
2

您可以使用自定义NumberFormatInfo. 然后将其ToString“n”格式说明符一起使用:

NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberGroupSeparator = "/";
nfi.NumberDecimalDigits = 0;   // otherwise the "n" format specifier adds .00
Console.Write(123456789.ToString("n", nfi));  // 123/456/789
于 2013-10-28T10:02:13.937 回答