I would like to ask what should I do to get the decimal points to show when dividing 2 integers.
Here's the details
int a = 25;
int b = 3;
decimal div = a / b;
Console.WriteLine("Quotient: " div); // 8
The problem is it only shows
Quotient = 8
But it requires us to output 15 decimal places which values at 8.333333333333334
What would be the proper way to do this?
This topic is about operators and expressions
CodePudding user response:
int a = 25;
int b = 3;
double div = (double)a / b;
Console.WriteLine("Quotient: " div); // 8
decimal div = (decimal)a / b;
Quotient while using decimal type: 8.333333333333333333333333333
double div = (double)a / b;
Quotient while using double type: 8.333333333333334
CodePudding user response:
If you want just to get decimal
you should cast (note, that 25 / 3 == 8
, when 25m / 3 == 8.33333333...
):
decimal div = ((decimal)a) / b;
In general case, if you want to print arbitrary number of digits
after decimal point you can loop and build the string:
int digits = 8; // number of digits after decimal separator we want to print
int a = 25;
int b = 3;
StringBuilder sb = new StringBuilder();
sb.Append(a / b);
for (int i = 0, r = Math.Abs(a % b); i < digits && r != 0; i, r = r * 10 % b) {
if (i == 0)
sb.Append(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
sb.Append(r * 10 / b);
}
Console.WriteLine($"Quotient: {sb.ToString()}");