Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if decimal contains decimal places by looking at the bytes

Tags:

c#

decimal

There is a similar question in here. Sometimes that solution gives exceptions because the numbers might be to large.

I think that if there is a way of looking at the bytes of a decimal number it will be more efficient. For example a decimal number has to be represented by some n number of bytes. For example an Int32 is represented by 32 bits and all the numbers that start with the bit of 1 are negative. Maybe there is some kind of similar relationship with decimal numbers. How could you look at the bytes of a decimal number? or the bytes of an integer number?

like image 898
Tono Nam Avatar asked Apr 17 '12 19:04

Tono Nam


People also ask

Can a byte contain decimals?

A byte is a group of 8 bits. A bit is the most basic unit and can be either 1 or 0. A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.

How many decimal places is 8 bytes?

Floating point numbers are stored in four or eight bytes. Internally, eight-byte numbers are rounded to fifteen decimal digits.

How many bytes is a decimal?

The maximum number of bytes the database server uses to store a decimal value is 17. One byte is used to store the exponent and sign, leaving 16 bytes to store up to 32 digits of precision. If you specify a precision of 32 and an odd scale, however, you lose 1 digit of precision.


2 Answers

If you are really talking about decimal numbers (as opposed to floating-point numbers), then Decimal.GetBits will let you look at the individual bits of a decimal. The MSDN page also contains a description of the meaning of the bits.

On the other hand, if you just want to check whether a number has a fractional part or not, doing a simple

var hasFractionalPart = (myValue - Math.Round(myValue) != 0)

is much easier than decoding the binary structure. This should work for decimals as well as classic floating-point data types such as float or double. In the latter case, due to floating-point rounding error, it might make sense to check for Math.Abs(myValue - Math.Round(myValue)) < someThreshold instead of comparing to 0.

like image 88
Heinzi Avatar answered Oct 11 '22 16:10

Heinzi


If you want a reasonably efficient way of getting the 'decimal' value of a decimal type you can just mod it by one.

decimal number = 4.75M;
decimal fractionalPart = number % 1; 
Console.WriteLine(fractionalPart); //will print 0.75

While it may not be the theoretically optimal solution, it'll be quite fast, and almost certainly fast enough for your purposes (far better than string manipulation and parsing, which is a common naive approach).

like image 41
Servy Avatar answered Oct 11 '22 18:10

Servy