Limiting Decimal Points in Java

Limiting the decimal points/places of a double/float value is very important mostly when you are dealing with average or amount. Usually, the JVM presents the maximum number of decimal places depending on the type used. Apparently, having more than three decimal points could be disturbing. Other languages like Turbo C/C++ deals with this by just simply adding the limit keywords (dot + number of decimal places + the charcter ‘F’) In Java, there are two ways to do it:

USING THE ‘setScale’ METHOD IN ‘BigDecimal’ CLASS Let us take this code snippet for instance:

double num = 4.00900990;
int decimalPlace = 2;
BigDecimal bd = new BigDecimal(num);
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);
System.out.println (bd);

In this code, the ‘num’ variable’s decimal value needs to be limited into 2 decimal places. To do this, the BigDecimal class under the java.math package should be used. After instantiating an object (‘bd’), you will now call the setScale method that accepts the ‘decimalPlace” which is 2 and the constant value BigDecimal.ROUND_UP for rounding up the values. The value with only 2 decimal places will then be printed in the console. This scheme in Java is quite complicated.

USING THE ‘System.out.format()’ METHOD

This apparently is the easiest way. The method takes two arguments: the output format and the string to display. Here’s an example that adds a dollar sign and commas to the display of an integer:

int accountBalance = 5005;
System.out.format(“Balance: $%,d%n”, accountBalance);

This code produces the following output:

Balance: $5,005

The formatting string begins with a percent sign (“%”) followed by one or more flags. The “%,d” code displays a decimal with commas dividing each three digits. The “%n” code displays a newline character. The next example displays the value of pi to 11 decimal places:

double pi = Math.PI;
System.out.format(“%.11f%n”, pi);

The output:
3.14159265359

4 Comments

  1. Hey man. Cheers…srsly, why was this so hard for me to remember and find on google. You’ve allowed me to go to bed.

  2. [...] For all the info, I read it here [...]

  3. very interesting, but I don’t agree with you
    Idetrorce

  4. A little over one year later, I echo Dirk.


Comments RSS TrackBack Identifier URI

Leave a comment