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

Gustav Brock Gustav at cactus.dk
Sat Aug 30 05:10:04 CDT 2008


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-VB mailing list