简体   繁体   中英

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. 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.

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

What the Round method does is that it returns a new double that is rounded. Here is what you need to do:

wifeSpending = Math.Round(wifeSpending, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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