I’m creating a RandomDecimal function that allows you to specify a max value and the precision of the decimal. However, if the last random digit that is chosen happens to be zero, it is dropped and the precision is off. Is it possible to not lose this zero? I tried converting it to a string then back to a decimal but it’s still dropped.
public static decimal RandomDecimal(int maxValue, int precision)
{
decimal result = new Random().Next(maxValue);
if (maxValue == 0)
{
return result;
}
int i = 1;
decimal digit = 0;
while (i <= precision)
{
digit = new Random().Next(10);
digit = (digit / (Convert.ToDecimal(Math.Pow(10, i))));
result = result + digit;
i++;
}
// if (digit == 0)
// {
// string resultstring = Convert.ToString(result) + '0';
// result = Convert.ToDecimal(resultstring);
// } This code doesn't do anything because the zero is still dropped.
return result;
}
If you want a representation of a number that has not only a value, but knows how many significant digits it has you are better off using something other than
double/float/decimal. You’ll want to create your own type that has both a value and aSignificantDigitsproperty.You simply want information
decimalwasn’t designed to have users using. In certain situations (where you have no leading/trailing zeros) you coincidentally end up with the same result despite [decimal] not knowing the information, but that’s irrelevant to you solving your problem.