我如何简单地输出一笔金额?

时间:2016-06-21 06:55:34

标签: c# decimal

我开始尝试学习代码,使用visual studio和c#book。它没有讨论如何将双倍金额更改为一美元金额。 以下是我到目前为止的程序(作业)。如何更改输出的格式(不使用system.globalization添加;)或者输出将始终读取1.1作为$ 1.10和1.5678作为$ 1.57。例如,如果我说我每小时10点50分工作39小时。

    {
        //Declare all variables:
        double Hours;
        double Rate;
        double GrossPay;
        double FederalTax;
        double StateTax;
        double SocialSecurity;
        double NetPay;
        double TotalTax;

        //Introduction:
        Console.WriteLine("Welcome to the Pay Calculator!!!");

        //User input of hours:
        Console.WriteLine("Please enter the hours you worked this pay period: ");
        Hours = Convert.ToDouble(Console.ReadLine());

        //User input for rate:
        Console.WriteLine("Please enter your rate of pay: ");
        Rate = Convert.ToDouble(Console.ReadLine());

        //Calculations
        GrossPay = Hours * Rate;
        FederalTax = GrossPay * 0.20d;
        StateTax = GrossPay * 0.05d;
        SocialSecurity = GrossPay * 0.062d;
        NetPay = GrossPay - FederalTax - StateTax - SocialSecurity;
        TotalTax = FederalTax + StateTax + SocialSecurity;

        //OutPut
        Console.WriteLine($"Your gross pay is: ${GrossPay}");
        Console.WriteLine($"Your federal tax obligation is: ${FederalTax}");
        Console.WriteLine($"Your state tax obligation is: ${StateTax}");
        Console.WriteLine($"Your social security obligation is: ${SocialSecurity}");
        Console.WriteLine($"Your total tax obligation is: $ {TotalTax}");
        Console.WriteLine($"This will bring your total net pay to: ${NetPay}");

        Console.ReadKey();
    }

3 个答案:

答案 0 :(得分:2)

如果要格式化为货币值,则应使用ToString("C")。首先将以下行添加到using语句中:

using System.Globalization;

然后:

Console.WriteLine(FavoriteNumber.ToString("C", CultureInfo.GetCultureInfo("en-US")));

结果:

$11.88

答案 1 :(得分:0)

这很简单 只需使用string.format函数为字符串

提供自定义格式

示例:

decimal[] amounts = { 16305.32m, 18794.16m };

Console.WriteLine("   Beginning Balance           Ending Balance");

Console.WriteLine("   {0,-28:C2}{1,14:C2}", amounts[0], amounts[1]);

此代码将显示此输出:

// Displays:

//        Beginning Balance           Ending Balance

//        $16,305.32                      $18,794.16    

答案 2 :(得分:0)

使用以下格式说明符的ToString(" C",en-US)。 123.456(" C",en-US) - > $ 123.46 更多信息: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx