C# Math.Round very long double - not working - c#

here is what I'm trying to do:
double result = Math.Pow((1 + 8), 60) - 1;
And the result variable is:
1.7970102999144311E+57 double
And trying to:
Math.Round(result, 5);
Returns same : 1.7970102999144311E+57 double
I'd like to round it to 1.79701 for example
Any solutions ?

You're misunderstanding what you're seeing.
1.7970102999144311E+57
Is scientific notation for
1797010299914431100000... (with 41 trailing zeros).
It is a whole number, thus rounding it to 5 decimal places will correctly return the same value.
What you want to do is format the output of the number
String.Format(CultureInfo.InvariantCulture, "{0:0.#####E+0}", result);
Which returns 1.79701E+57. Note that this is a very different number from 1.79701

The problem you're having is that Math.Round rounds things to the right of the decimal point. For example if you're dealing with currency and you perform an operation that leaves you with $1.5234524, you would use:
Math.Round(1.5234524,2);
// output 1.52
The number you're dealing with is actually scientific notation for a very large number with nothing to the right of the decimal point. This is why the result of Math.Round is the same as the input.

The earlier comments and answers are correct. But to get what you are trying to achieve you can use the following:
double result = Math.Pow((1 + 8), 60) - 1;
string s = String.Format("{0:E5}", result);
double d = Double.Parse(s);

Related

Rounding Off a double value using Math.Round

I have a double value: 0.314285 which I want to Round off to 5 decimal places. From a mathematical point of view my expectant result is: 0.31429. In my code I use the Math.Round with MidPointRounding.AwayFromZero parameter overload, the resultant output being: 0.31428.
Is there another way to implement to have the output result as: 0.31429??
You should read the rounding and precision article. The real representation of your number in memory can be something like 0.3142849999999999, and therefore you are getting 0.31428 result. Using a decimal type can help to solve this issue
var value = 0.314285m;
var result = Math.Round(value, 5, MidpointRounding.AwayFromZero); //0.31429
public static double RoundUp(double i, int decimalPlaces)
{
var power = Math.Pow(10, decimalPlaces);
return Math.Ceiling(i * power) / power;
}
RoundDown(0.314285, 5); //0.31429
Math.Round(decimal number to round, int number of decimal places)
I think this should work for what you are trying to do.

Exponents in C#

int trail = 14;
double mean = 14.00000587000000;
double sd = 4.47307944700000;
double zscore = double.MinValue;
zscore = (trail - mean) / sd; //zscore at this point is exponent value -1.3122950464645662E-06
zscore = Math.Round(zscore, 14); //-1.31229505E-06
Math.Round() also keeps the exponent value. should zscore.ToString("F14") be used instead of Math.Round() function to convert it to non-exponent value? Please explain.
These are completely independant concerns.
Math.Round will actually return a new value, rounded to the specified decimal (ar at least, as near as one can do with floating point).
You can reuse this result value anywhere, and show it with 16 decimals precision if you want, but it's not supposed to be the same as the original one.
The fact that it is displayed with exponent notation or not has nothing to do with Round.
When you use ToString("F14") on a number, this is a display specification only, and does not modify the underlying value in any way. The underlying value might be a number that would or would not display as exponential notation otherwise, and may or may actually have 14 significant digits.
It simply forces the number to be displayed as a full decimal without exponent notation, with the number of digits specified. So it seems to be what you actually want.
Examples :
(executable online here : http://rextester.com/PZXDES55622)
double num = 0.00000123456789;
Console.WriteLine("original :");
Console.WriteLine(num.ToString());
Console.WriteLine(num.ToString("F6"));
Console.WriteLine(num.ToString("F10"));
Console.WriteLine(num.ToString("F14"));
Console.WriteLine("rounded to 6");
double rounded6 = Math.Round(num, 6);
Console.WriteLine(rounded6.ToString());
Console.WriteLine(rounded6.ToString("F6"));
Console.WriteLine(rounded6.ToString("F10"));
Console.WriteLine(rounded6.ToString("F14"));
Console.WriteLine("rounded to 10");
double rounded10 = Math.Round(num, 10);
Console.WriteLine(rounded10.ToString());
Console.WriteLine(rounded10.ToString("F6"));
Console.WriteLine(rounded10.ToString("F10"));
Console.WriteLine(rounded10.ToString("F14"));
will output:
original :
1,23456789E-06
0,000001
0,0000012346
0,00000123456789
rounded to 6
1E-06
0,000001
0,0000010000
0,00000100000000
rounded to 10
1,2346E-06
0,000001
0,0000012346
0,00000123460000

C# divide operator not Working [duplicate]

How do I divide two integers to get a double?
You want to cast the numbers:
double num3 = (double)num1/(double)num2;
Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:
double num3 = (double)num1/num2;
For more information see:
Dot Net Perls
Complementing the #NoahD's answer
To have a greater precision you can cast to decimal:
(decimal)100/863
//0.1158748551564310544611819235
Or:
Decimal.Divide(100, 863)
//0.1158748551564310544611819235
Double are represented allocating 64 bits while decimal uses 128
(double)100/863
//0.11587485515643106
In depth explanation of "precision"
For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats and doubles and this one where he talks about decimals.
cast the integers to doubles.
Convert one of them to a double first. This form works in many languages:
real_result = (int_numerator + 0.0) / int_denominator
var firstNumber=5000,
secondeNumber=37;
var decimalResult = decimal.Divide(firstNumber,secondeNumber);
Console.WriteLine(decimalResult );
var result = decimal.ToDouble(decimal.Divide(5, 2));
I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen.
But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.
The easiest way to do that is adding decimal places to your integer.
Ex.:
var v1 = 1 / 30 //the result is 0
var v2 = 1.00 / 30.00 //the result is 0.033333333333333333
In the comment to the accepted answer there is a distinction made which seems to be worth highlighting in a separate answer.
The correct code:
double num3 = (double)num1/(double)num2;
is not the same as casting the result of integer division:
double num3 = (double)(num1/num2);
Given num1 = 7 and num2 = 12:
The correct code will result in num3 = 0.5833333
Casting the result of integer division will result in num3 = 0.00

Format a double to two digits after the comma without rounding up or down

I have been searching forever and I simply cannot find the answer, none of them will work properly.
I want to turn a double like 0.33333333333 into 0,33 or 0.6666666666 into 0,66
Number like 0.9999999999 should become 1 though.
I tried various methods like
value.ToString("##.##", System.Globalization.CultureInfo.InvariantCulture)
It just returns garbage or rounds the number wrongly.
Any help please?
Basically every number is divided by 9, then it needs to be displayed with 2 decimal places without any rounding.
I have found a nice function that seems to work well with numbers up to 9.999999999
Beyond that it starts to lose one decimal number. With a number like 200.33333333333
its going to just display 200 instead of 200,33. Any fix for that guys?
Here it is:
string Truncate(double value, int precision)
{
string result = value.ToString();
int dot = result.IndexOf(',');
if (dot < 0)
{
return result;
}
int newLength = dot + precision + 1;
if (newLength == dot + 1)
{
newLength--;
}
if (newLength > result.Length)
{
newLength = result.Length;
}
return result.Substring(0, newLength);
}
Have you tried
Math.Round(0.33333333333, 2);
Update*
If you don't want the decimal rounded another thing you can do is change the double to a string and then get get a substring to two decimal places and convert it back to a double.
doubleString = double.toString();
if(doubleString.IndexOf(',') > -1)
{
doubleString = doubleString.Substring(0,doubleString.IndexOf(',')+3);
}
double = Convert.ToDouble(doubleString);
You can use a if statement to check for .99 and change it to 1 for that case.
Math.Truncate(value * 100)/100
Although I make no guarantees about how the division will affect the floating point number. Decimal numbers can often not be represented exactly in floating point, because they are stored as base 2, not base 10, so if you want to guarantee reliability, use a decimal, not a double.
Math.Round((decimal)number, 2)
Casting to a decimal first will avoid the precision issues discussed on the documentation page.
Math.Floor effectively drops anything after the decimal point. If you want to save two digits, do the glitch operation - multiply then divide:
Math.Floor(100 * number) / 100
This is faster and safer than doing a culture-dependent search for a comma in a double-converted-to-string, as accepted answer suggests.
you can try one from below.there are many way for this.
1.
value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
inputvalue=Math.Round(123.4567, 2) //"123.46"
3.
String.Format("{0:0.00}", 123.4567); // "123.46"
4.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568

Fix numbers count after point for decimal

How I can fix digits count after point for decimal type WITHOUT ROUNDING
in C#.
For example:
decimal coords = 47.483749999999816; (part of geographic coordinates)
I need to stay only 6 digits after point: 47.483749
You might use
decimal truncated = Math.Truncate(coords * 1000000m) / 1000000m;
or maybe
decimal truncated = Math.Truncate(coords / 0.000001m) * 0.000001m;
Of these two, I have come to prefer the latter. The number 0.000001m is represented internally as the mantissa 1 together with the scale 6, so dividing and multiplying by it is effectively just a move of the decimal point by six places.
The method where you multiply by 0.000001m in the end tends to give a result with exactly six digits after the decimal point, even with trailing zeroes if necessary. For example coords = 1.23m will lead to truncated being 1.230000m.
As noted in the comments, the above techniques will both lead to an OverflowException if coords is too huge (more than one millionth of the decimal.MaxValue).
For completeness, here are a couple of other solutions:
decimal truncated = coords - coords % 0.000001m;
This seems to work fine. The number of trailing zeroes will not always be correct though, but I believe it gives the same result wrt. the == operator (or decimal.Equals).
Finally, you can use:
decimal truncated = Math.Round(coords - 0.0000005m, 6, MidpointRounding.AwayFromZero);
but that works only for non-negative coords.
If what you really need is a formatted string, call a ToString overload on truncated. But beware, as I indicated, of trailing zeroes. If you use .ToString("F6") there should always be exactly six decimals.
Of course you can also use string manipulation for the truncating. It would go something like:
string coordsString = coords.ToString(CultureInfo.InvariantCulture);
int idxOfPoint = coordsString.IndexOf(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator);
if (idxOfPoint != -1 && coordsString.Length > 6 + 1 + idxOfPoint)
coordsString = coordsString.Remove(6 + 1 + idxOfPoint);
// coordsString is now truncated correctly.
// If you need a decimal, use decimal.Parse(coordsString)
Very tricky, and not suggested, but I don't really know what solution are you looking for (since you're avoiding rounding):
double k = 47.483749999999816;
k = double.Parse(Regex.Replace(k.ToString(), #"(\d+\.\d{6})(.\d+)", x => x.Groups[1].Value));
Console.WriteLine(k);
that prints
47.483749
You can use
decimal.Round( 47.483749999999816, 6)

Categories