3

This seems like it should be really simple but I'm having trouble finding the answer online.

What's the proper way to define a Decimal variable and initialize it with constant value in C++/CLI?

In C# it would be:

decimal d = 1.1M;

In C++/CLI I've been doing:

Decimal d = (Decimal)1.1;

Which works for some numbers, but I suspect it's just converting from double.

I notice there's a constructor: Decimal(int, int, int, bool, unsigned char) but was hoping there's an easier way to deal with large specific numbers.

  • 3
    The C++/CLI compiler does not have additional literal types beyond those offered by C++. An arbitrary workaround it is to initialize with 11 and divide by 10. – Hans Passant Sep 26 '12 at 16:36
  • I guess if I used 64-bit numbers there should always be a power of 10 that works. Although, it appears Int64.MaxValue is smaller than Decimal.MaxValue so this would only work for a certain range of values. I was also thinking d = Decimal::Parse("1.1"); but efficiency likely wouldn't be good and the compiler won't check it. –  Sep 26 '12 at 16:51

1 Answers1

1

You are indeed casting the number. You can, as mentioned, parse from a string or divide integers, or you may want to use the BigRational data type. Independently of the option you choose you may create a utility method in a static class to do it so you don't have to repeat it all the time.

You can also suggest on the VS UserVoice Site to allow number sufixes like in C#.

JMCF125
  • 378
  • 3
  • 18
  • Just `BigInteger` by itself really helps. `(Decimal)(BigInteger(10000)*BigInteger(42))/(Decimal)((BigInteger(100)*BigInteger(100))` gets me pretty far... Pardon for not accepting yet, I've got to think about your answer a bit. I guess I should have RTM. –  Mar 31 '13 at 17:33
  • @ebyrob, take the time you want, I actually once had this problem, and just divided integers (as the `BigInteger`s in your example). I added the `BigRational` type as another way to do it, as the others were already in the comments. And I would post the suffix idea on UserVoice, but I posted a few and already used up my votes. Also, what do you mean by "should have RTM"? – JMCF125 Mar 31 '13 at 20:25
  • 1
    RTM - read the manual. BigInteger was there in .Net 4.0 all along, I just didn't even know about it. –  Apr 01 '13 at 01:56