C# 用c语言格式化一个数字#
我想用逗号分隔一个数字。我试过很多方法来做这件事。但是没有起作用 它已经转换成字符串,现在我想格式化“tot”C# 用c语言格式化一个数字#,c#,.net,string,formatting,cultureinfo,C#,.net,String,Formatting,Cultureinfo,我想用逗号分隔一个数字。我试过很多方法来做这件事。但是没有起作用 它已经转换成字符串,现在我想格式化“tot” 您可以将tot字符串转换为数值,然后使用string.Format获取所需格式: string tot = "19950000"; string output = string.Format("{0:n2}", Convert.ToInt32(tot)); Debug.WriteLine(output); //19,950,000.00 on my machine 或者: strin
您可以将
tot
字符串转换为数值,然后使用string.Format
获取所需格式:
string tot = "19950000";
string output = string.Format("{0:n2}", Convert.ToInt32(tot));
Debug.WriteLine(output); //19,950,000.00 on my machine
或者:
string output2 = Convert.ToInt32(tot).ToString("n2");
它们都是特定于文化的,因此可能在不同的用户机器上显示不同(例如,印度文化将显示1,99,50000.00
)
如果要强制使用三位逗号分组,则可以指定要使用的区域性:
string output2 = Convert.ToInt32(tot).ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
//19,950,000.00 on any machine
听起来您的tot
可能不是一个数值,因此您应该在尝试格式化它之前检查此项:
string tot = "19950000";
int totInt;
if (Int32.TryParse(tot, out totInt))
{
string output = totInt.ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
MessageBox.Show(output);
}
else
{
MessageBox.Show("tot could not be parsed to an Int32");
}
您可以将
tot
字符串转换为数值,然后使用string.Format
获取所需格式:
string tot = "19950000";
string output = string.Format("{0:n2}", Convert.ToInt32(tot));
Debug.WriteLine(output); //19,950,000.00 on my machine
或者:
string output2 = Convert.ToInt32(tot).ToString("n2");
它们都是特定于文化的,因此可能在不同的用户机器上显示不同(例如,印度文化将显示1,99,50000.00
)
如果要强制使用三位逗号分组,则可以指定要使用的区域性:
string output2 = Convert.ToInt32(tot).ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
//19,950,000.00 on any machine
听起来您的tot
可能不是一个数值,因此您应该在尝试格式化它之前检查此项:
string tot = "19950000";
int totInt;
if (Int32.TryParse(tot, out totInt))
{
string output = totInt.ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
MessageBox.Show(output);
}
else
{
MessageBox.Show("tot could not be parsed to an Int32");
}
您的实际输出和预期输出是什么?我希望标签中的值显示如下19950000.00您应该显示您尝试过的代码以及在最新编辑中“不起作用”的内容,是不是应该是
LB2.Text=totVal代码>?您的实际输出和预期输出是什么?我希望标签中的值显示如下19950000.00您应该显示您尝试过的代码以及在最新编辑中“不起作用”的内容,不是吗代码>?我也尝试过,但创建了一个异常。我已经上传了当前代码,请看一看。GetData GetData=new GetData();string tot=Convert.ToString(getData.Total_额外(月));string totVal=string.Format(“0:n2”,Convert.ToInt32(tot));LB2.Text=totVal.ToString();在这里,您尝试使用浮点,但我想格式化字符串值Matt Wilko-我尝试了使用和不使用花括号。我发现输入错误type@MattWilko:伙计,这就是你在回答中输入的代码,我只想说我已经尝试了你的代码,效果很好。OP:)的屏幕截图我也试过了,但产生了一个异常。我已经上传了当前代码,请看一看。GetData GetData=new GetData();string tot=Convert.ToString(getData.Total_额外(月));string totVal=string.Format(“0:n2”,Convert.ToInt32(tot));LB2.Text=totVal.ToString();在这里,您尝试使用浮点,但我想格式化字符串值Matt Wilko-我尝试了使用和不使用花括号。我发现输入错误type@MattWilko:伙计,这就是你在回答中输入的代码,我只想说我已经尝试了你的代码,效果很好。OP的截图:)