首页 > 解决方案 > C#。格式化我的变量以在小数点后显示 2 位数字。可以在 Console.WriteLine() 方法中完成吗

问题描述

using System;

namespace Toy_Shop
{
    class Program
    {
        static void Main(string[] args)
        {
            //pricing of the toys in the toy shop
            const double puzzlePrice = 2.60;
            const double dollPrice = 3.00;
            const double teddyBearPrice = 4.10;
            const double minionPrice = 8.20;
            const double toyTruckPrice = 2.00;

            //vacationPrice is the amount Petya needs to go on a vacation
            //the rest is the amount of each toy thta has been ordered
            double vacationPrice = double.Parse(Console.ReadLine());
            int puzzlesSold = int.Parse(Console.ReadLine());
            int dollsSold = int.Parse(Console.ReadLine());
            int teddyBearsSold = int.Parse(Console.ReadLine());
            int minionsSold = int.Parse(Console.ReadLine());
            int toyTrucksSold = int.Parse(Console.ReadLine());

            int totalToys = puzzlesSold + dollsSold + teddyBearsSold + minionsSold + toyTrucksSold;
            double total = puzzlesSold * puzzlePrice + dollsSold * dollPrice + teddyBearsSold * teddyBearPrice + minionsSold * minionPrice + toyTrucksSold * toyTruckPrice;

            if(totalToys >= 50)
            {
                double totalWithDiscount = total - (total * 0.25);
                double finalIncome = totalWithDiscount - (totalWithDiscount * 0.1);
                bool vacation = finalIncome > vacationPrice;
                double moneyNeeded = (finalIncome - vacationPrice) * -1;
                
                if(vacation)
                    Console.WriteLine($"Yes! {finalIncome - vacationPrice} lv left.");
                else
                    Console.WriteLine($"Not enough money! {moneyNeeded} lv needed");
            }

            else
            {
                double finalIncome = total - (total * 0.1);
                bool vacation = finalIncome > vacationPrice;
                double moneyNeeded = (finalIncome - vacationPrice) * -1;

                if (vacation)
                    Console.WriteLine($"Yes! {finalIncome - vacationPrice} lv left.");
                else
                    Console.WriteLine($"Not enough money! {moneyNeeded} lv needed");

            }
            
        }
    }
}

标签: c#function

解决方案


static void Main(string[] args)
{
  float value = 145.352f;
  Console.WriteLine(string.Format("Number are: {0:N2} ", value));
  Console.ReadKey();
}
// Output: Number are: 145,35

更多信息标准数字格式字符串


推荐阅读