如何格式化C#中的美分和美元?如何将一个转换为另一个?

时间:2011-02-03 02:45:34

标签: c# decimal currency

如果我在C#或Java中写了25美分的东西,我怎么把它转换为$ .25?

3 个答案:

答案 0 :(得分:9)

您应该使用Decimal数据类型,然后使用一种标准表示法,而不是尝试将美分兑换成美元:

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

输出为:Amount: $0.25;

答案 1 :(得分:5)

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;
    }
}

你可以像这样使用它

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

答案 2 :(得分:1)

我认为这是最佳答案我用数组写

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();






    }