简体   繁体   English

转换为十进制数字并将格式数字转换为小数点后两位

[英]Convert to decimal & format number to 2 digits after decimal mark

The output from the code below produces a decimal number with 13 digits after decimal mark. 下面代码的输出产生一个十进制数字,该数字在小数点后是13位数字。 I want to round off that number to only 2 digits after decimal mark. 我想将该数字四舍五入到小数点后仅两位数。 I've tried to use the Decimal.Round Method to no avail, apparently I'm not using it right. 我试图使用Decimal.Round Method无济于事,显然我没有正确使用它。

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)
        {

            TimeSpan time = TimeSpan.FromSeconds(1000);

            double downloadTime = time.TotalHours;

            double money = 50;

            double wifeSpending = money * downloadTime;



            Console.WriteLine(Convert.ToDecimal(wifeSpending));

        }
    }
}

As I understand from your comments, you are doing it like this: 据您的评论所知,您正在这样做:

Math.Round(wifeSpending, 2);

The Round method does not change the variable that you pass in. It even couldn't if it wanted to because the double value is passed by value (not by reference). Round方法不会更改您传入的变量。如果愿意,它甚至无法这样做,因为double值是按值(而不是按引用)传递的。

What the Round method does is that it returns a new double that is rounded. Round方法的作用是返回一个新的四舍五入的double Here is what you need to do: 这是您需要做的:

wifeSpending = Math.Round(wifeSpending, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM