索引和长度必须引用该字符串内的位置
索引和长度必须引用该字符串内的位置。
参数名: length
public string MoneyConvert(string money)
{
string n5 = string.Empty;
string changestr = string.Empty;
string bigstr = string.Empty;
string smallstr = string.Empty;
int len = 0;
if (money.IndexOf(".") > 0)
{
n5 = money.Substring(0, money.IndexOf("."));
}
else
{
n5 = money;
}
len = n5.Length;
changestr = "";
bigstr = "";
smallstr = "";
while (len > 3)
{
bigstr = n5.Substring(0, len - 3);
smallstr = n5.Substring(len - 3, len);
if (changestr != "")
{
changestr = smallstr + "," + changestr;
}
else
{
changestr = smallstr;
}
len -= 3;
}
if (money.IndexOf(".") > 0)
{
if (changestr != "")
{
changestr = n5.Substring(0, len) + "," + changestr + money.Substring(money.IndexOf("."), money.Length);
}
else
{
changestr = n5.Substring(0, len) + money.Substring(money.IndexOf("."), money.Length);
}
}
else
{
if (changestr != "")
{
changestr = n5.Substring(0, len) + "," + changestr;
}
else
{
changestr = n5.Substring(0, len);
}
}
return changestr;
}
smallstr = n5.Substring(len - 3, len);这一句的时候报错。求解决!
这个是用于做金额转换的,例如,1000 用这个函数转换后就是1,000 每隔三位加一个,号
smallstr = n5.Substring(len - 3<0?0:len - 3, len>n5.Length-1?n5.Length-1:len)这样写的话输入1000是没问题,但超过就会报错。
------解决方案--------------------
你可以直接用ToString()
格式说明符 说明 示例 输出
C 货币 2.5.ToString("C") ¥2.50
D 十进制数 25.ToString("D5") 00025
E 科学型 25000.ToString("E") 2.500000E+005
F 固定点 25.ToString("F2") 25.00
G 常规 2.5.ToString("G") 2.5
N 数字 2500000.ToString("N") 2,500,000.00
X 十六进制 255.ToString("X") FF
具体代码就是
C# code
string temp = "2500000.0056";
int count = Regex.Match(temp,@"(?<=\.)\d+").Value.Length;
string ss = double.Parse(temp).ToString("N" + count);//2,500,000.0056
------解决方案--------------------
len改为3
------解决方案--------------------
我晕,每隔3位+逗号直接用ToString("N0")不就行了,还弄出那么一大段的方法来-_-`
C# code
static void Main(string[] args)
{
int a=Convert.ToInt32(Console.ReadLine());
Console.Write(a.ToString("N0"));
Console.ReadKey();
}