Question

In C#, I have a long that I need to convert to a decimal. The problem is that I want to put the decimal point at a specific position in the long.

For example, let's say I have the following number as a long:

long l = 123456789

When converting to a decimal with the floating point at the third position, I want to have the following:

decimal d = 123456.789

To give you an example, the function would ideally be something like the BigDecimal.valueOf in Java that allows you to give a long and a position to put the decimal point, and it returns the correct value.

I know one of the solution would be to format the long as a string with the correct decimal point position and then convert it back to a decimal. Another solution would be to multiply the long by 10-Decimal places wanted, but I'm wondering if there's a better alternative to this.

Was it helpful?

Solution

You could use the Decimal constructor that takes different constituent parts. You'll need to do a bit of bitshifting to get the exponent into all the relevant sections, but that shouldn't be too hard. If you know that your value won't be more than 62 bits in magnitude, that would make things easier, too.

OTHER TIPS

Why don't you divide by 1000 (or 10^N where N is the number of decimal places)?

long l = 123456789L;
int decplaces = 3;

decimal divisor =(decimal) Math.Pow(10, decplaces);
decimal d = l/divisor;

You could just write a loop to multiply by 0.1m the correct number of times, i.e. numberOfDecimalPlacesWanted iterations of the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top