Reputation: 13
I have to create a simple number rounding tool for my school project.
It lets the user decide how many decimals to round a given number.
I can't get my code to round the user's input (number
) to the given decimals (decimalammount
).
It's just showing the default 2 decimals every time :( Any help would be much appreciated!
static void Main(string[] args)
{
Console.Clear();
while (true)
{
string input;
decimal number;
int decimalammount;
Console.WriteLine("Rounderuperer");
Console.WriteLine("Please enter the number you wish to round:");
input = Console.ReadLine();
number = decimal.Parse(input);
Console.WriteLine("Please enter the number of decimals you wish to round to:");
input = Console.ReadLine();
decimalammount = int.Parse(input);
Console.WriteLine("{0:f} Rounded to {1:g} decimals = {2:f}", number, decimalammount, Math.Round(number, decimalammount, MidpointRounding.AwayFromZero));
Console.WriteLine("Press <Spacebar> to round another number . . .");
if (Console.ReadKey().Key != ConsoleKey.Spacebar)
break;
}
}
Upvotes: 1
Views: 166
Reputation: 23732
You Problem is the f
for the format of numbers. The documentation of numeric format strings says the following:
"F" or "f" Fixed-point Result: Integral and decimal digits with optional negative sign.
Supported by: All numeric types.
Precision specifier: Number of decimal digits.
Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.
The NumberFormatInfo.NumberDecimalDigit documentation tells us:
The number of decimal places to use in numeric values. The default for InvariantInfo is 2.
So this is the reason why you get always those 2 decimal places.
The simplest solution would be to remove the format entirely. Actually also in the first number, since you probably want it to be displayed with all its decimals
Console.WriteLine("{0} Rounded to {1:g} decimals = {2}", number, decimalammount, Math.Round(number, decimalammount, MidpointRounding.AwayFromZero));
Upvotes: 2