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?.
Latest posts by Wayan (see all)
- How do I split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023