如何使用.00结尾格式化整数

时间:2015-12-23 17:58:39

标签: c# numeric

我想要达到以下目的:无论打印到控制台的数字是什么,它都必须在小数点后有 2 数字。当结果是十进制数时,程序将其四舍五入到小数点后的2位数,所以这很好。然而,问题在于整个数字并没有附加到它们上面,即100个被打印为 100 ,而不是 100.00 ,因为我想要它至。我已经在这方面挣扎了很长一段时间,所以我的任何帮助都将受到高度赞赏。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TorrentPirate
{
    class Program
    {
        static void Main(string[] args)
        {     
           int megabytes = int.Parse(Console.ReadLine());        
           int cinemaPricePerMovie = int.Parse(Console.ReadLine());     
           int wifeSpendingHour = int.Parse(Console.ReadLine());
           TimeSpan time = TimeSpan.FromSeconds(megabytes/2);
           double downloadTime = time.TotalHours;
           double downloadPrice = wifeSpendingHour * downloadTime;
           int NumberOfMoviesDownloaded = megabytes / 1500;
           double cinemaPrice = NumberOfMoviesDownloaded * cinemaPricePerMovie;

            if (cinemaPrice >= downloadPrice)
            {
                downloadPrice = Math.Round(downloadPrice, 2);
                Console.WriteLine("{0} -> {1}lv", "mall", Convert.ToDecimal(downloadPrice));
                    }
            else
            {
                cinemaPrice = Math.Round(cinemaPrice, 2);
                Console.WriteLine("{0} -> {1}lv", "cinema", Convert.ToDecimal(cinemaPrice));
            }

        }
    }
}

3 个答案:

答案 0 :(得分:2)

为什么不将它显示为字符串?

Console.WriteLine("{0} -> {1}lv", "mall", downloadPrice.ToString("#.##"));

答案 1 :(得分:2)

您可以使用.ToString("0.00")

Console.WriteLine("{0} -> {1}lv", "mall", downloadPrice.ToString("0.00"));

或者,您只需使用格式说明符N2

Console.WriteLine("{0} -> {1:N2}lv", "mall", downloadPrice);

请参阅Standard Numeric Format Strings

答案 2 :(得分:1)

users