amt has asked for the wisdom of the Perl Monks concerning the following question:

I am writing an invoicing script, and find myself with fractions of cents that in Excel are formatted to currency values. This creates blatent aritmetic errors as the display value and the actual value are different.

I am looking to use BigInt to round my values to 2 decimal places. Can I use BigInt to do this, or would I have to use BigFloat?

The documentation for BigInt states that I can set precision to -2 for the class for all my number objects, would this be the best approach?
amt.

perlcheat

2006-07-05 Retitled by planetscape, as per Monastery guidelines

( keep:0 edit:5 reap:0 )

Original title: 'Using Math::BigInt'

  • Comment on Dealing with rounding errors (Using Math::BigInt)

Replies are listed 'Best First'.
Re: Dealing with rounding errors (Using Math::BigInt)
by jdtoronto (Prior) on Jul 05, 2006 at 15:36 UTC
Re: Dealing with rounding errors (Using Math::BigInt)
by swampyankee (Parson) on Jul 05, 2006 at 15:54 UTC

    Well, BigInt only deals with integers, so the "accuracy" and "precision" settings will be ignored if negative (see bigint and Math::BigInt).

    Historically, currency calculations were done in BCD, which is one approach.

    My suggestion would be to do all the calculations as integers, in mils (tenths of a cent), rounding with explicit code, i.e., don't rely on rounding rules buried in sprintf, bigint, or bigfloat, and converting to dollars and cents when required. If you're doing this for tax calculations, I would expect that the appropriate tax authorities will have tables listing how much tax (in cents) is applicable to purchases of a given amount. They may also have rounding rules they require to be followed.


    added in edit

    Or heed jdtoronto's suggestion and look at Math::Currency

    emc

    e(π√−1) = −1