关于十进制:如何格式化C#中的美分和美元?

How do I format cents and dollars in C#? How do I convert one to the other?

如果我用C或Java编写了25美分的东西,我怎么把它转换成25美元?


您可能应该使用Decimal数据类型,然后不要试图将美分转换为美元,而是使用一个标准符号:

1
2
Decimal amount = .25M;
String.Format("Amount: {0:C}", amount);

输出为:Amount: $0.25


1
2
3
4
5
6
7
8
9
10
11
class Money
{
    public int Dollar {get; set;}
    public int Cent { get; set;}

    public Money(int cents)
    {
        this.Dollar = Math.Floor(cents/100);
        this.Cent = cents%100;
    }
}

你可以这样使用它

1
2
3
int cents = Convert.ToInt32(Console.Readline("Please enter cents to convert:"))
Money money = new Money(cents);
Console.Writeline("$" + money.Dollar +"." + money.Cent);


我想这是我用数组写的最佳答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("Please input your cent or dollar");

        int coins = int.Parse(Console.ReadLine());

        int[] dollars = new int[2];

         dollars[0] = coins / 100;
         dollars[1] = coins % 100;



        Console.WriteLine("{0} dollar and {1} coins", dollars[0], dollars[1]);
        Console.ReadLine();






    }