Decimal scale

You don’t get an ArithmeticException if you don’t specify the scale in a division operation but some care is still needed…

@isTest
static void testDecimalArithmetic() {

    System.assertEquals(0, 1 / 3);
    System.assertEquals(0.25, 1.0 / 4.0);

    // Default scale is big...
    Decimal unlimited = Decimal.valueOf('0.333333333333333333333333333333333');

    System.assertEquals(unlimited, 1.0 / 3.0);
    System.assertEquals(unlimited, 1 / 3.0);
    System.assertEquals(unlimited, 1.0 / 3);
    System.assertEquals(unlimited, Decimal.valueOf('1') / Decimal.valueOf('3'));
    System.assertEquals(unlimited, Decimal.valueOf('1.0000') / Decimal.valueOf('3.00'));
    System.assertEquals(unlimited, Decimal.valueOf('1.00') / Decimal.valueOf('3.0000'));

    Integer scale = 4;
    Decimal limited = Decimal.valueOf('0.3333');

    System.assertEquals(limited, Decimal.valueOf('1').divide(Decimal.valueOf('3'), scale));
    System.assertEquals(limited, Decimal.valueOf('1.000000').divide(Decimal.valueOf('3.00000'), scale));
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s