On Monday, 6 June 2016 at 19:30:52 UTC, Observer wrote:
On Monday, 6 June 2016 at 18:55:22 UTC, Ola Fosheim Grøstad
wrote:
On Monday, 6 June 2016 at 18:36:37 UTC, Observer wrote:
It's more complicated than that. Part of what you need is to
be able to declare a variable as (say) having two significant
fractional digits, and have the rounding rules be implicitly
applied when saving to that variable, producing an exact
representation of the rounded result in storage.
Yes, but if you want accurate representation of two fractional
digits on storage only, then it makes most sense to do all
calculations on cents (scale everything by 100) and store as
integers.
That's only a workaround. It's probably best to think of
decimal
arithmetic as an accountant would, not as a computer geek would.
Intermediate arithmetic results should perhaps also be rounded/
truncated, though it depends on the particular calculation. For
instance, I might have an interest percentage that gets carried
to 4 sig figs (fractional digits), but when applied to a
currency
amount with only 2 sig figs, the result should end up with 2 sig
figs, not 6. And then that result should continue to be used in
later arithmetic in the same larger expression, even without an
explicit save operation to invoke the rounding/truncation. If
you tried this using float for the percentage and integer for
the amount, once the conversion to float happened it would not
revert in the middle of the expression.
Also, keeping values as only integers complicates input/output
formatting. I want 123456 pennies to show up as either 1234.56
or perhaps 1,234.56 (at least, I want that punctuation in a U.S.
locale), and this should happen without my needing to manually
rescale during i/o operations.
Entirely agree.
Scaling everything internally to force things to integers, and
then re-scaling on output is just bending the language because it
cannot properly address the problem. The result is just creating
something more to go wrong - consider large accounting program
maintained over several years, not always by original author.
If we allow _int foo;_ to declare an integer variable foo, then
suggest we have
_dec bar(a,b);_ to declare a decimal variable bar with a units in
total length, b units of decimal places.
D language then defines how (for example) assignment is carried
out (by default), and also provides mechanisms for alternatives
(ie some sort of dec_trunc() and dec_round() functions).