自定义字符串格式 0,0,带斜杠或反斜杠
本文关键字:字符串 格式 自定义 | 更新日期: 2023-09-27 18:37:17
我有一个WPF文本框,用户可以在其中键入数字。 现在我正在寻找一种字符串格式,可以将 TextBox 编号分隔每 3 个点(如 0,0),但我想要带有斜杠或反斜杠或其他字符的单独文本。 我们不知道我们的数字有多少点。
我正在寻找字符串格式而不是Linq解决方案等。 我阅读了Microsoft帮助,但找不到任何方法。
样本 = 123456789 ==> 123/456/789(好) --- 123,456,789(坏)
更新:
谢谢大家,但我搜索一些类似这个字符串格式= {}{0:0,0} 等的东西。 我的意思是不想使用像正则表达式、替换或 linq 或任何 C# 代码这样的字符串。 我想使用像{#,#}等这样的字符串。 在我的帖子中看到微软链接,我需要为我的问题创建一个字符串。
由于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));
自定义NumberFormatInfo
。然后使用它与"n"格式的说明符进行ToString
:
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
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
*/
为您 - 将数字组分隔符属性设置为"/"
更新另一个示例
var t = long.Parse("123/456/789",NumberStyles.Any, new NumberFormatInfo() { NumberGroupSeparator = "/" });
var output = string.Format(new NumberFormatInfo() { NumberGroupSeparator="/"}, "{0:0,0}", t);