M.DeMar
M.DeMar

Reputation: 9

C# Issue implementing rounding

New to coding and C#. I've written a piece of code that I'm running into issues with rounding out to 2 decimals. My code is designed to take todays date and subtract it by a future date. The code itself works; but I wanted it to look cleaner than (Days until completion: 115.11560043243519). Below is my code:

Console.WriteLine("Newport to Owensboro:");
var currentDate = DateTime.Now;
var endDate = new DateTime(2022, 10, 30);
double remainingDays = endDate.Subtract(currentDate).TotalDays;
Console.WriteLine("Days until completion: {0}\n", remainingDays);
Math.Round(remainingDays, 2);

Upvotes: 0

Views: 50

Answers (1)

TimS
TimS

Reputation: 2113

You can use the Fixed-Point Format specifier to format the days within the string, without the call to Math.Round.

Console.WriteLine("Days until completion: {0:F2}\n", remainingDays);

If you did want to use Math.Round, you need to take the return value from it and use that in your string.

double remainingDays = endDate.Subtract(currentDate).TotalDays;
double remainingDaysRounded = Math.Round(remainingDays, 2);
Console.WriteLine("Days until completion: {0}\n", remainingDaysRounded);

However I would suggest you use format specifiers if your purpose is solely to format the value for a string.

Upvotes: 0

Related Questions