如何将string格式化为金钱
我有一个像000000000100
这样的string,我想将其转换为1.00,反之亦然。
前导零将被删除,后两位是小数。
我举出更多的例子:
000000001000 <=> 10.00 000000001005 <=> 10.05 000000331150 <=> 3311.50
下面是我正在尝试的代码,它给我没有小数的结果:
amtf = string.Format("{0:0.00}", amt.TrimStart(new char[] {'0'}));
将string转换为小数,然后除以100,并应用货币格式string:
string.Format("{0:#.00}", Convert.ToDecimal(myMoneyString) / 100);
按照要求编辑删除货币符号,并将其转换为小数点。
您将需要先将其转换为小数点,然后使用金钱格式进行格式化。
EX:
string myValue = "000000001000"; decimal moneyvalue = 1921.39m; string moneyValue = String.Format("{0:C}", moneyvalue);
有用!
decimal moneyvalue = 1921.39m; string html = String.Format("Order Total: {0:C}", moneyvalue); Console.WriteLine(html);
产量
Order Total: $1,921.39
decimal value = 0.00M; value = Convert.ToDecimal(12345.12345); Console.WriteLine(value.ToString("C")); //OutPut : $12345.12 Console.WriteLine(value.ToString("C1")); //OutPut : $12345.1 Console.WriteLine(value.ToString("C2")); //OutPut : $12345.12 Console.WriteLine(value.ToString("C3")); //OutPut : $12345.123 Console.WriteLine(value.ToString("C4")); //OutPut : $12345.1234 Console.WriteLine(value.ToString("C5")); //OutPut : $12345.12345 Console.WriteLine(value.ToString("C6")); //OutPut : $12345.123450
控制台输出:
string s ="000000000100"; decimal iv = 0; decimal.TryParse(s, out iv); Console.WriteLine((iv / 100).ToString("0.00"));
//Extra currency symbol and currency formatting: "€3,311.50": String result = (Decimal.Parse("000000331150") / 100).ToString("C"); //No currency symbol and no currency formatting: "3311.50" String result = (Decimal.Parse("000000331150") / 100).ToString("f2");
一旦你有你的string在双/十进制到一个特定的区域使用正确的格式
double amount = 1234.95; amount.ToString("C") // whatever the executing computer thinks is the right fomat amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie")) // €1,234.95 amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es")) // 1.234,95 € amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) // £1,234.95 amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au")) // $1,234.95 amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) // $1,234.95 amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca")) // $1,234.95
试试像这样简单
var amtf = $"{Convert.ToDecimal(amt):#0.00}";
先将stringparsing为小数点。
尝试这样的事情:
decimal moneyvalue = 1921.39m; string html = String.Format("Order Total: {0:C}", moneyvalue); Console.WriteLine(html);
var tests = new[] {"000000001000", "000000001005", "000000331150"}; foreach (var test in tests) { Console.WriteLine("{0} <=> {1:f2}", test, Convert.ToDecimal(test) / 100); }
既然你没有要求货币符号,我用“f2”而不是“C”
尝试
amtf = amtf.Insert(amtf.Length - 2, ".");
你也可以这样做:
string.Format("{0:C}", amt)