C# 如何将字符串格式化为钱

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10615405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:31:11  来源:igfitidea点击:

How to format string to money

c#

提问by Alvin

I have a string like 000000000100, which I would like to convert to 1.00 and vice versa.

我有一个像 的字符串000000000100,我想将其转换为 1.00,反之亦然。

Leading zero will be remove, last two digit is the decimal.

前导零将被删除,最后两位是小数。

I give more example :

我举更多例子:

000000001000 <=> 10.00
000000001005 <=> 10.05
000000331150 <=> 3311.50

Below is the code I am trying, it is giving me result without decimal :

下面是我正在尝试的代码,它给了我没有小数的结果:

amtf = string.Format("{0:0.00}", amt.TrimStart(new char[] {'0'}));

采纳答案by Lloyd Powell

Convert the string to a decimal then divide it by 100 and apply the currency format string:

将字符串转换为小数,然后除以 100 并应用货币格式字符串:

string.Format("{0:#.00}", Convert.ToDecimal(myMoneyString) / 100);

Edited to remove currency symbol as requested and convert to decimal instead.

编辑以根据要求删除货币符号并转换为十进制。

回答by greijner

Parse to your string to a decimal first.

首先将您的字符串解析为小数。

回答by Mohammed Swillam

you will need to convert it to a decimal first, then format it with money format.

您需要先将其转换为小数,然后使用货币格式对其进行格式化。

EX:

前任:

decimal decimalMoneyValue = 1921.39m;
string formattedMoneyValue = String.Format("{0:C}", decimalMoneyValue);

a working example: https://dotnetfiddle.net/soxxuW

一个工作示例:https: //dotnetfiddle.net/soxxuW

回答by Piotr Justyna

//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");

回答by Habib

    string s ="000000000100";
    decimal iv = 0;
    decimal.TryParse(s, out iv);
    Console.WriteLine((iv / 100).ToString("0.00"));

回答by thejartender

Try something like this:

尝试这样的事情:

decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);

回答by Antony Scott

var tests = new[] {"000000001000", "000000001005", "000000331150"};
foreach (var test in tests)
{
    Console.WriteLine("{0} <=> {1:f2}", test, Convert.ToDecimal(test) / 100);
}

Since you didn't ask for the currency symbol, I've used "f2" instead of "C"

由于您没有要求提供货币符号,因此我使用了“f2”而不是“C”

回答by Pera

try

尝试

amtf =  amtf.Insert(amtf.Length - 2, ".");

回答by Hymanal

you can also do :

你也可以这样做:

string.Format("{0:C}", amt)

回答by Jorge Luis Pe?a Lopez

It works!

有用!

decimal moneyvalue = 1921.39m; 
string html = String.Format("Order Total: {0:C}", moneyvalue); 
Console.WriteLine(html);

Output

输出

Order Total: ,921.39