Is there a way to round a decimal to the nearest decimal place? I need code that will take an unknown number (unknown number of decimal places) and round it to the nearest decimal place.
decimal number = 0.0000029;
// *magic*
// number = 0.000003;
Is there a way to round a decimal to the nearest decimal place? I need code that will take an unknown number (unknown number of decimal places) and round it to the nearest decimal place.
decimal number = 0.0000029;
// *magic*
// number = 0.000003;
Use the .Round() method:
Decimal number = 0.0000029;
//Count the number of decimal places:
int placeCount = BitConverter.GetBytes(decimal.GetBits(number)[3])[2];
//Output: 7
//round your decimal to the nearest decimal (one less than the original count)
Decimal number2 = Decimal.Round(number, placeCount - 1);
Debug.WriteLine(number2.ToString());
//Output: 0.000003