[dba-VS] [dba-VB] C#, mantissa, math fun

Gustav Brock gustav at cactus.dk
Sun Oct 15 10:27:18 CDT 2017


Hi all

I noticed, that this method will strip leading zeroes from the decimal part.
For example, an input of 1234.056789 will return 56789 and not 056789.

Thus, the result must be a string:

double number = -1234.056789;
string mantissa = string.Empty;
decimal fraction = (decimal)number % 1;
if (fraction != 0)
{
        mantissa = Math.Abs(fraction).ToString().Substring(2);
}
Console.WriteLine(mantissa);
Console.ReadKey();

// -> 056789

/gustav
________________________________________
Fra: dba-vb-bounces at databaseadvisors.com <dba-vb-bounces at databaseadvisors.com> på vegne af Gustav Brock
Sendt: 30. august 2008 12:10:04
Til: dba-vb at databaseadvisors.com
Emne: Re: [dba-VB] C#, mantissa, math fun

Hi all

(blush) ... if no decimals exist (number is an integer) that one-liner will fail. So check for zero decimals:

  double number = -1234.56789;
  int mantissa = 0;
  decimal fraction = (decimal)number % 1;
  if (fraction != 0)
  {
      mantissa = Convert.ToInt32(Math.Abs(fraction).ToString().Substring(2));
  }

/gustav

>>> Gustav at cactus.dk 17-08-2008 17:13 >>>
Hi all

Delphi people know this as Fract, the decimal part of a decimal number.

C# does not contain a direct method to extract that, so I thought of some smart math way to do so as I try too to avoid number handling by string conversion as it often turns into some "dirty" operation.
By second thought you - as a human - easily can extract the mantissa but you do that by looking at the full number as a string. So why not ask the machine to do the same - and simple string handling is actually extremely fast for small strings like here, while raising a number to the power of something (which is a math method) is slower.

So, inspired by this link:

  http://bytes.com/forum/thread563673.html

I found this simple one-liner which handles both negative and positive numbers:

double number = -1234.56789;
int mantissa = Convert.ToInt32((Math.Abs((decimal)number) % 1).ToString().Substring(2));

mantissa -> 56789

Of course, if you expect to use it a lot, wrap it into a utility class.

Still, I wonder if some clever byte manipulation method would exist.

/gustav


More information about the dba-VS mailing list