C# Int and math not returning full value
Int64 c1 = Convert.ToInt64(csvdeep[1]);
Int64 division = 1024;
string results = Math.Abs(c1 / division / division / division).ToString();
My c1
is 1020184开发者_如何转开发1664
and results
is "9"
.
I'd perfer to get the 2nd two decimal places so my real result would be 9.50. Any tips on how I could get the 2 decimal places?
That is the result of integer division in .NET - when dividing two integers you always get an integer.
You need at least one of the operands to be a floating point type (float, double, decimal) in order for the result to be a floating point.
Int64 c1 = Convert.ToInt64(csvdeep[1]);
double division = 1024.0m;
string results = Math.Abs(c1 / division / division / division).ToString();
The result of this will probably have more decimal places than you want so you will need to use a format string in the call to ToString
:
string results = Math.Abs(c1 / division / division / division).ToString("0.00");
You could try:
string results = Math.Abs(((double)c1)/division/division/division)
.ToString("0.00");
By converting the first value (c1
) to a floating point value rather than an integer, you force the result of the division to become floating point as well.
That would then force the use of Math.Abs(double)
rather than Math.Abs(long)
Try
Int64 c1 = 10201841664;
Int64 division = 1024;
string results = Math.Abs((decimal)c1/division/division/division).ToString("0.00");
You could even go for
Int64 c1 = 10201841664;
Int64 division = 1024;
string results = Math.Abs((double)c1 / Math.Pow((double)division, 3)).ToString("0.00");
You are using integer division here. That's why its not showing any decimal places.
精彩评论