Using format flags to format negative number in parentheses

In this example we are going to learn to use a java.util.Formatter to format negative number in parentheses. The Formatter can use a format flags to format a value. To display a negative number in parentheses we can use the ( flag. This flag display negative number inside parentheses instead of using the - symbol.

The following code snippet below will show you how to do it. We start the example by using the Formatter object and simplified using the format() method of the String class.

package org.kodejava.util;

import java.util.Formatter;
import java.util.Locale;

public class FormatNegativeNumber {
    public static void main(String[] args) {
        // Creates an instance of Formatter, format the number using the
        // format and print out the result.
        Formatter formatter = new Formatter();
        formatter.format("%(,.2f", -199.99f);
        System.out.println("number1 = " + formatter);

        // Use String.format() method instead of creating an instance of
        // Formatter. Format a negative number using Germany locale.
        String number2 = String.format(Locale.GERMANY, "%(,8.2f", -49.99);
        System.out.println("number2 = " + number2);

        // Format number using Indonesian locale. The thousand separator is "."
        // in Indonesian number.
        String number3 = String.format(new Locale("id", "ID"), "%(,d", -10000);
        System.out.println("number3 = " + number3);
    }
}

The result of this code snippet:

number1 = (199.99)
number2 =  (49,99)
number3 = (10.000)

How do I parse negative number in parentheses?

In financial application negative numbers are often represented in parentheses. In this post we will learn how we can parse or convert the negative number in parentheses to produce the represented number value. To parse text / string to a number we can use the java.text.DecimalFormat class.

Beside number in parentheses, in this example we also parse negative number that use the minus sign with the currency symbol like $. Let’s jump to the code snippet below:

package org.kodejava.text;

import java.text.DecimalFormat;

public class NegativeNumberParse {
    // Pattern for parsing negative number.
    public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
    public static final String PATTERN2 = "$#,##0.00;-$#,##0.00";

    public static void main(String[] args) throws Exception {
        DecimalFormat df = new DecimalFormat(PATTERN1);

        String number1 = "(1000)";
        String number2 = "(1,500.99)";

        System.out.println("number1 = " + df.parse(number1));
        System.out.println("number2 = " + df.parse(number2));

        df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern(PATTERN2);

        String number3 = "-$1000";
        String number4 = "-$1,500.99";

        System.out.println("number3 = " + df.parse(number3));
        System.out.println("number4 = " + df.parse(number4));
    }
}

And here are the results of our code snippet above:

number1 = -1000
number2 = -1500.99
number3 = -1000
number4 = -1500.99

If you need to display or format negative numbers in parentheses you can take a look at the following example How do I display negative number in parentheses?.

How to use underscore in numeric literals?

Writing a long sequence of numbers in a code is a hard stuff to read. In the new feature introduced by JDK 7 we are now allowed to write numeric literals using the underscore character to break the numbers to make it easier to read.

You can see how to use underscore in numeric literals in the following examples. And you’ll see it for yourself that it really makes numbers easier to read.

package org.kodejava.basic;

public class UnderscoreNumericExample {
    public static void main(String[] args) {
        // Write numeric literals using underscore as an easier way
        // to read long numbers.
        int maxInt = 2_147_483_647;
        int minInt = -2_147_483_648;

        if (maxInt == Integer.MAX_VALUE) {
            System.out.println("maxInt = " + maxInt);
        }

        if (minInt == Integer.MIN_VALUE) {
            System.out.println("minInt = " + minInt);
        }

        // Write numbers in binary or hex literals using the
        // underscores.
        int maxIntBinary = 0B111_1111_1111_1111_1111_1111_1111_1111;
        int maxIntHex = 0X7____F____F____F____F____F____F____F;

        System.out.println("maxIntBinary = " + maxIntBinary);
        System.out.println("maxIntHex    = " + maxIntHex);
    }
}

The results of the code snippet:

maxInt = 2147483647
minInt = -2147483648
maxIntBinary = 2147483647
maxIntHex    = 2147483647

How do I raised a number to the power of n?

The static method Math.pow(double a, double b) can be used to raise the value specified in the a, the first argument, (the base), to the power of the value specified in b, the second argument, (the exponent). The exponent tells us how many times the base should be multiplied by itself. So, if I have the number of 5, and I want to raise it to the 3rd power, it means that I have to multiply 5 by itself for 3 times.

There are some special cases for the Math.pow() method, as you can read in the Javadocs, here four of them taken from the Javadocs:

  • If the second argument is positive or negative zero, then the result is 1.0.
  • If the second argument is 1.0, then the result is the same as the first argument.
  • If the second argument is NaN, then the result is NaN.
  • If the first argument is NaN and the second argument is nonzero, then the result is NaN.

You can read more detail about the Math.pow() method on the following Javadocs, Math.pow().

Let’s see a code snippet as an example:

package org.kodejava.math;

public class PowerExample {

    public static void main(String[] args) {
        double cubeRoot = 5d;

        // Get the cubed number of cube root
        // x cubed = x^3 (multiplication three times)
        double cubed = Math.pow(cubeRoot, 3);
        System.out.println(cubeRoot + " cubed is " + cubed);

        // Raised to zero
        System.out.println("Math.pow(2, 0): " + Math.pow(2, 0));

        // Raised to one
        System.out.println("Math.pow(2, 1): " + Math.pow(2, 1));

        // Raised to NaN
        System.out.println("Math.pow(2, Double.NaN): " + Math.pow(2, Double.NaN));

        // NaN raised to the nonzero exponent
        System.out.println("Math.pow(Double.NaN, 2): " + Math.pow(Double.NaN, 2));
    }
}

Our program print the following output:

5.0 cubed is 125.0
Math.pow(2, 0): 1.0
Math.pow(2, 1): 2.0
Math.pow(2, Double.NaN): NaN
Math.pow(Double.NaN, 2): NaN

How do I round a number?

The example below show you some methods of the Math class that can be used to round the value of a number. These methods are Math.ceil(), Math.floor() and Math.round().

package org.kodejava.math;

public class GetRoundedValueExample {

    public static void main(String[] args) {
        Double number = 1.5D;

        // Get the smallest value that is greater than or equal to the
        // argument and is equal to a mathematical integer
        double roundUp = Math.ceil(number);
        System.out.println("Result of rounding up of " + number + " = " + roundUp);

        // Get the largest value that is less than or equal to the
        // argument and is equal to a mathematical integer
        double roundDown = Math.floor(number);
        System.out.println("Result of rounding down of " + number + " = " + roundDown);

        // Get the closest long value to the argument
        long round1 = Math.round(number);
        System.out.println("Rounding result of " + number + " (in long) = " + round1);

        // Get the closest int value to the argument
        int round2 = Math.round(number.floatValue());
        System.out.println("Rounding result of " + number + " (in int) = " + round2);
    }
}

Here are the result of the program:

Result of rounding up of 1.5 = 2.0
Result of rounding down of 1.5 = 1.0
Rounding result of 1.5 (in long) = 2
Rounding result of 1.5 (in int) = 2

How do I sort string of numbers in ascending order?

In the following example we are going to sort a string containing the following numbers "2, 5, 9, 1, 10, 7, 4, 8" in ascending order, so we will get the result of "1, 2, 4, 5, 7, 8, 9, 10".

package org.kodejava.util;

import java.util.Arrays;

public class SortStringNumber {
    public static void main(String[] args) {
        // We have some string numbers separated by comma. First we
        // need to split it, so we can get each individual number.
        String data = "2, 5, 9, 1, 10, 7, 4, 8";
        String[] numbers = data.split(",");

        // Convert the string numbers into Integer and placed it into
        // an array of Integer.
        Integer[] intValues = new Integer[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intValues[i] = Integer.parseInt(numbers[i].trim());
        }

        // Sort the number in ascending order using the
        // Arrays.sort() method.
        Arrays.sort(intValues);

        // Convert back the sorted number into string using the
        // StringBuilder object. Prints the sorted string numbers.
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < intValues.length; i++) {
            Integer intValue = intValues[i];
            builder.append(intValue);
            if (i < intValues.length - 1) {
                builder.append(", ");
            }
        }
        System.out.println("Before = " + data);
        System.out.println("After  = " + builder);
    }
}

When we run the program we will get the following output:

Before = 2, 5, 9, 1, 10, 7, 4, 8
After  = 1, 2, 4, 5, 7, 8, 9, 10

How do I format a message that contains number information?

This example show you how to use java.text.MessageFormat class to format a message that contains numbers.

package org.kodejava.text;

import java.text.MessageFormat;
import java.util.Locale;

public class MessageFormatNumber {
    public static void main(String[] args) {

        // Set the Locale for the MessageFormat.
        Locale.setDefault(Locale.US);

        // Use the default formatting for number.
        String message = MessageFormat.format("This is a {0} and {1} numbers",
                10, 75);
        System.out.println(message);

        // This line has the same format as above.
        message = MessageFormat.format("This is a {0,number} and {1,number} " +
                "numbers", 10, 75);
        System.out.println(message);

        // Format a number with 2 decimal digits.
        message = MessageFormat.format("This is a formatted {0, number,#.##} " +
                "and {1, number,#.##} numbers", 25.7575, 75.2525);
        System.out.println(message);

        // Format a number as currency.
        message = MessageFormat.format("This is a formatted currency " +
                        "{0,number,currency} and {1,number,currency} numbers",
                25.7575, 25.7575);
        System.out.println(message);

        // Format numbers in percentage.
        message = MessageFormat.format("This is a formatted percentage " +
                "{0,number,percent} and {1,number,percent} numbers", 0.10, 0.75);
        System.out.println(message);
    }
}

The result of the program are the following lines:

This is a 10 and 75 numbers
This is a 10 and 75 numbers
This is a formatted 25.76 and 75.25 numbers
This is a formatted currency $25.76 and $25.76 numbers
This is a formatted percentage 10% and 75% numbers

How do I decode string to integer?

The static Integer.decode() method can be used to convert a string representation of a number into an Integer object. Under the cover this method call the Integer.valueOf(String s, int radix).

The string can start with the optional negative sign followed with radix specified such as 0x, 0X, # for hexadecimal value, 0 (zero) for octal number.

package org.kodejava.lang;

public class IntegerDecode {
    public static void main(String[] args) {
        String decimal = "10"; // Decimal
        String hex = "0XFF"; // Hex
        String octal = "077"; // Octal

        Integer number = Integer.decode(decimal);
        System.out.println("String [" + decimal + "] = " + number);

        number = Integer.decode(hex);
        System.out.println("String [" + hex + "] = " + number);

        number = Integer.decode(octal);
        System.out.println("String [" + octal + "] = " + number);
    }
}

The result of the code snippet above:

String [10] = 10
String [0XFF] = 255
String [077] = 63

How do I generate a random array of numbers?

Using java.util.Random class we can create random data such as boolean, integer, floats, double. First you’ll need to create an instance of the Random class. This class has some next***() methods that can randomly create the data.

package org.kodejava.util;

import java.util.Arrays;
import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random r = new Random();

        // generate some random boolean values
        boolean[] booleans = new boolean[10];
        for (int i = 0; i < booleans.length; i++) {
            booleans[i] = r.nextBoolean();
        }
        System.out.println(Arrays.toString(booleans));

        // generate a uniformly distributed int random numbers
        int[] integers = new int[10];
        for (int i = 0; i < integers.length; i++) {
            integers[i] = r.nextInt();
        }
        System.out.println(Arrays.toString(integers));

        // generate a uniformly distributed float random numbers
        float[] floats = new float[10];
        for (int i = 0; i < floats.length; i++) {
            floats[i] = r.nextFloat();
        }
        System.out.println(Arrays.toString(floats));

        // generate a Gaussian normally distributed random numbers
        double[] doubles = new double[10];
        for (int i = 0; i < doubles.length; i++) {
            doubles[i] = r.nextGaussian();
        }
        System.out.println(Arrays.toString(doubles));
    }
}

The result of the code snippet above are:

[true, true, false, true, false, true, true, false, false, true]
[34195704, 1462972230, -475641915, -1531017612, 332184915, 1555901473, -276309016, 1433394157, -451221924, -1178823255]
[0.3040716, 0.28814012, 0.34028566, 0.021003246, 0.49158317, 0.37954164, 0.5403056, 0.54187375, 0.7157934, 0.5964742]
[1.051268591002577, -1.1283332046139989, 0.8351395528722437, -0.24598168031182968, 0.7123515366756693, -0.9661681996105319, -1.6107009669125059, 0.43994917963255387, 1.1309345726165914, 1.2321618489324313]

For an example to create random number using the Math.random() method see How do I create random number?.

How do I parse a number for a locale?

package org.kodejava.text;

import java.util.Locale;
import java.text.NumberFormat;
import java.text.ParseException;

public class LocaleNumberParse {
    public static void main(String[] args) {
        try {
            // In this example we are trying to parse a number string in a
            // defined format. Basically we want to covert the string for a
            // locale into a correct number value.
            Number number =
                NumberFormat.getNumberInstance(Locale.JAPAN).parse("25,000.75");

            // Just do some stuff with the number from the parse process
            if (number instanceof Long) {
                System.out.println("This number is instanceof Long and the " +
                    "value is: " + number.longValue());
            } else if (number instanceof Double) {
                System.out.println("This number is instanceof Double and the " +
                    "value is: " + number.doubleValue());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}

The code snippet print out the following result:

This number is instanceof Double and the value is: 25000.75