2

I need to store an arbitrary length decimal in c++. The following is the structure we are considering:

<NumberAsString(char*), DecimalAt(int32)>

An example of this would be:

1.00003940400
<"100003940400", 11>

0.0004
<"0004", 4>

10
<"10", 0>

Does this seem like a good way to store a decimal? Is there a better way to do this?

Another possible approach would be similar to how the "money modules" often work in javascript, for example, giving the number as an int "in cents" -- $102.25 being stored as 10225. And we'd store it like this:

<int64, int64> # the second int64 would be the decimal places

For example, if we allow "5 decimal places of precision", then we would store:

12.250
<12, .250E5> // or <12, 25000>

Which approach would be better -- or perhaps use something else entirely?

David542
  • 96,524
  • 132
  • 375
  • 637
  • Well, you're gonna have to convert `char *` to `int` or `float` or `double` the minute you want to run calculations on them. But I mean that looks cool. –  Jun 10 '19 at 04:47
  • You may find useful this other question and it's answers: https://stackoverflow.com/questions/14096026/c-decimal-data-types#14096071 – Heladio Amaya Jun 10 '19 at 04:55
  • @Chipster what about the second approach then? – David542 Jun 10 '19 at 05:11
  • That could work. The nice thing about the first one is that it's more like scientific notation (sort of, not exactly) if that's how your brain works and thinks. The other way allows for not needing a conversion, which is nice. Honestly, I think this question is subjective as to which one is better. They both have their advantages and disadvantages. –  Jun 10 '19 at 05:16
  • There are dozens of libraries for that, are you sure you need to create another one? – n. 'pronouns' m. Jun 10 '19 at 05:27
  • @n.m. I've looked at boost and bde...so no I'm open to anything really. But before choosing one I'm kind of trying to understand how they should be stored and where they might be different, etc. – David542 Jun 10 '19 at 05:33
  • Storing digits is messy and uses only ~4% of the storage capacity. If you can waste the space, you can store sequences of one-digit numbers instead. If you want to save space, you can work in base 256. – molbdnilo Jun 10 '19 at 05:35
  • @molbdnilo there could be ~ 100M numbers or so that would need to fit in memory, so I don't know about doing a storage-heavy solution. – David542 Jun 10 '19 at 05:36

0 Answers0