armin
armin

Reputation: 39

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

If I have something written as 25 cents in either C# or Java, how would I convert that to read $.25?

Upvotes: 2

Views: 20227

Answers (3)

ali
ali

Reputation: 65

I think this is Best Answer I write with Array

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






    }

Upvotes: 1

Joe
Joe

Reputation: 11637

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

and u can use it like so

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

Upvotes: 5

George Stocker
George Stocker

Reputation: 57872

You should probably use the Decimal datatype, and then instead of trying to convert cents to dollars, use one standard notation:

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

The output is: Amount: $0.25;

Upvotes: 9

Related Questions