How to get decimal value? [duplicate] - c#

This question already has answers here:
How do you round a number to two decimal places in C#?
(15 answers)
Closed 6 years ago.
I am measuring serverPerformance.
Right now I get this in milliseconds but I want to convert this into seconds when it is more or equal to 500 milliseconds.
I Accomplish this like this
public static string ConvertMillisecondsToSeconds(long milliseconds)
{
if(milliseconds >= 500)
return Math.Ceiling(TimeSpan.FromMilliseconds(milliseconds).TotalSeconds).ToString() + "s";
return milliseconds.ToString() + "ms";
}
My problem
When I return totalseconds without Math.ceiling I get for example:
0,846 seconds
When I use math.Ceiling method I get 1 second.
Desiered result
0,8 seconds.
basically im searching for a method that will return a decimal value, with 2 decimals.

var milliseconds = 0.846;
milliseconds.ToString("0.00"); // Gives 0.85

Related

Incorrect calculation in C# [duplicate]

This question already has answers here:
C# Getting strange results for a simple math operations
(4 answers)
Is floating point math broken?
(31 answers)
Closed 5 years ago.
Why (0.406 * 10000.0) returns 4060.0000000000005 instead of 4060.0 in C#
I have written a function which checks no. of decimals in a double value and below is the code I am using. The problem described in the above sentence occurs when value of d is 0.406 and values of n is 4 and the function returns true instead of false
I am open to using alternate solution.
public static bool HasMoreThanNDecimals(double d, int n)
{
return !(d * (double)Math.Pow(10, n) % 1 == 0);
}
Just use decimal type instead of double for more precision to get the desired result.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/921a8ffc-9829-4145-bdc9-a96c1ec174a5/decimal-vs-double-difference?forum=csharpgeneral

Float calculation showing difference. Positive showing negative? [duplicate]

This question already has answers here:
Always return positive value
(9 answers)
Closed 5 years ago.
I am calculating the difference between two numbers. If the calculation ends up being 5 - 10, it equals to "-5". If this is the case I need results to display/equal to "+5" , with the "+" sign.
I basically need reverse. So same if 10 - 5 quals to "5" I need it to display as "+5"
Code below I am using:
float rowresults = ROW1 - ROW2;
Textbox.text = rowresults.ToString();
Math.Abs is what you are looking for:
float rowresults = Math.Abs(ROW1 - ROW2);
And to add the "+"-sign to the front of the text (without changing your elsewise existing behaviour):
Textbox.text = "+" + rowresults.ToString();

Add decimal number to Date - C#

How to convert a decimal number (e.g. 2.5) to year and month (2 years and 6 months) and add it to a given date? I tried DateTime.TryParse and it didn't work.
If you are using it for years then multiply the float you have by 12. 2.5 becomes 30months. Then use the addmonths function. If I enter 5 then it will add 60 months which is 5 years
Usually you could just add a TimeSpan or use one of the Add methods, like this:
decimal yearsToAdd = (decimal)2.5;
int years = (int)Math.Floor(yearsToAdd);
decimal months = yearsToAdd - years;
int actualMonths = (int) Math.Floor(months * 12); // or Ceiling or Round
DateTime x = DateTime.Now.AddYears(years).AddMonths(actualMonths);
The problem is, that when you decimal doesn't yield an exacat number of months, how would you know how long e.g. half a month is?
28.0 / 2, 29.0 / 2, 30.0 / 2 or 31.0 / 2?
Would you take the length of the month you started with or one of the possible two months you end up with?
If you init date is dt than
dt = dt.AddMonths((int)(2.5*12));
decimal x =(decimal)2.5;
int nbYear = Convert.ToInt16(x);
var y = x - Math.Truncate(x);
int nbMonth =Convert.ToInt16 (y*12);
// MessageBox .Show (string.Format (" {0} years and {1} months ",nbYear ,nbMonth ));
DateTime dat=DateTime .Now ; // or given date
DateTime dat2 = dat.AddYears(nbYear).AddMonths(nbMonth);
If month is your smallest unit then the solution is, as pointed by many, to multiply number by 12. A more accurate alternative would be to use ticks.
decimal years=3.14592M; // No idea where this came from.
long ticks = (long)(356.0M * (decimal)TimeSpan.TicksPerDay * years);
DateTime futureDate=DateTime.Today.AddTicks(ticks);
Note that solution will not compensate for leap years. It is not difficult to extend it - you need to calculate number of leap years in the period and use average instead of 356.0M to calculate ticks per year (i.e. avg. number of days per year * ticks per day).

How to combine integers in c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Im looking for a way to combine my integers together.
I got 3 integers i want to make one from them.
All the integers are holding a time currency wich looks a little like this:
var date = DateTime.Now;
int timeHours = date.Hour;
I got the Hours, Minutes and Seconds and want to combine so they would look like this:
Hour : Minutes : Seconds
How can i combine the integers together to do that.
Note: I've looked on the internet but i could not get the information i was looking for.
This is what i looked at:
Combine two integers to create a unique number
How to combine 2 integers in order to get 1?
Combining these integers will generate a string, not an another integer. You can easily format your DateTime with ToString() method like;
var str = DateTime.Now.ToString("H':'m':'s"); // eg: 11:0:2
If you wanna get your hour, minute and second part with leading zeros for single digits, you can use HH:mm:ss format instead.
var str = DateTime.Now.ToString("HH':'mm':'ss"); // eg: 11:00:02
DateTime.Now already contains all information you need, date and time. All you need to do is format this information
There're many ways to pack two (or many) integers into one based
on their ranges, e.g.
int i1 = 123;
int i2 = 456;
// two 32-bit integers into 64-bit one
long result = (((long) i1) << 32) | i2;
In your particular case
int hours = 5;
int minutes = 10;
int seconds = 59;
int combined = hours * 3600 + minutes * 60 + seconds;
reverse:
int combined = 12345;
int seconds = combined % 60;
int minutes = (combined / 60) % 60;
int hours = combined / 3600;
you can try the below code i think it's useful
var date = DateTime.Now;
var result = date.Hour + ":" + date.Minute + ":" + date.Second;
Console.WriteLine(result);
A simple way using the base 10 number system is to just
var number = hours * 10000 + minutes * 100 + seconds
this returns a number like 150936 for 15:09:36
To convert back:
seconds = number % 100
minutes = (number / 100) % 100
hours = number / 10000
Note that this is obviously not the most efficient approach, but simple
You should cast to string with format function for example:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
Just to be complete:
format HH:mm:ss:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("HH:mm:ss");
format H:m:s:
string result = string.Format("{0}:{1}:{2}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("H:m:s");

How to get the round off value of a decimal in C# [duplicate]

This question already has answers here:
How do you round a number to two decimal places in C#?
(15 answers)
Closed 8 years ago.
I want to get the round off value of a decimal number Suppose I am getting 24.86 than i want to get 25 as final value
Look at Math.Round(decimal) and the overload which accepts a MidpointRounding argument.
Simply
Math.Round(24.86)
This will round you value to 25.
Your own logic will be
decimal d = 1.5m;
decimal r = d - Math.Truncate(d);
if (r > 0)
r = 1 - r;
decimal value = d + r;

Categories