【问题标题】:How do I format cents and dollars in C#? How do I convert one to the other?如何在 C# 中格式化美分和美元?如何将一种转换为另一种?
【发布时间】:2011-02-03 02:45:34
【问题描述】:

如果我用 C# 或 Java 写成 25 美分,我将如何将其转换为 $.25?

【问题讨论】:

    标签: c# decimal currency


    【解决方案1】:

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

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

    输出为:Amount: $0.25;

    【讨论】:

    • 用Decimal赚钱的重要原因:stackoverflow.com/questions/316727/…
    • @TheBigO 是的,我实际上在另一个用户在下面给出的现已删除的答案中链接到它。
    • 实际上,我反对使用 Decimal 来换取金钱(而是一种特定的货币类型,包括“所有细节支持”),但它比使用浮点数要好一些——它仍然是相对精确的并且在退化的情况下或极端情况下会表现出与使用浮点数相同的“问题”。
    • @pst Microsoft 似乎认为它是合适的。 msdn.microsoft.com/en-us/library/364x0z75%28v=vs.80%29.aspx
    • 一个非常人为的案例:decimal m = Decimal.MaxValue - 1; (m / 3m * 3m) == m; // false(尽管我认为这类似于说 GUID 很快就会“用完”)。此外,交易货币的规则可能相当复杂(谁得到拆分中的零钱?)并且可能存在最小的货币单位。当然,这个帖子/问题远低于这些范围。
    【解决方案2】:
    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);
    

    【讨论】:

    • 我们应该使用数组吗?
    • 好吧,这取决于您需要多少。你可以创建一个 List money = new List();存储很多这些
    • console.readline(frome user), console.writeline(你有 X cent , or x Dollar and x cent)
    • 您是在问如何将console.readline 和writeline 合并到其中吗?或者说你能做到?或者问你是否需要一个用于 readline 和 writeline 的数组?你的最终目标是什么?解析美分列表或一次从用户那里获取美分并立即打印出来?
    • 请编辑您的初始问题以准确询问您的需求。包含尽可能多的信息,以便我们为您提供帮助。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 1970-01-01
      • 2021-03-31
      • 2017-01-14
      • 1970-01-01
      • 2021-09-16
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多