View Javadoc

1   package fr.ove.utils;
2   
3   import java.text.NumberFormat;
4   
5   /***
6   *
7   * @author © 1999 DIRAT Laurent
8   * @version 2.0  28/06/1999
9   */
10  public class NumberUtils {
11      /***
12      * Analyzes a token and determines whether it is a number (integer or float) or
13      * not.<BR>
14      * If not, considers this token as a variable.
15      *
16      * @param token the token to anlazye.
17      * @return <CODE>true</CODE> if the token is a number. <CODE>false</CODE> otherwise.
18      */
19      public static boolean isNumber(String token) {
20          char oneChar;
21          
22          for (int i = 0; i < token.length(); i++) {
23              oneChar = token.charAt(i);
24              
25              if (!Character.isDigit(oneChar) && (oneChar != '.'))
26                  return false;
27          }
28          return true;
29      }
30      
31      /***
32      * Analyzes the token and determines wheter it is an integer or a float. We assume that
33      * the specified token is already a number.
34      * @param token the token to analyze.
35      * @return <CODE>true</CODE> if the token is a float. <CODE>false</CODE>
36      * if the token is an integer.
37      */
38      public static boolean isFloat(String token) {
39          for (int i = 0; i < token.length(); i++)
40              if (token.charAt(i) == '.')
41                  return true;
42                  
43          return false;
44      }
45      
46      /***
47      * Formats the specified double value with two digits after decimal place
48      * @param dValue the value to format.
49      */
50      public static String formatDouble(String dValue) {
51          NumberFormat form;
52          form = NumberFormat.getInstance();//get local number format instance
53          form.setMaximumFractionDigits(2);//set for 2 digits only after decimal place
54          form.setMinimumFractionDigits(1);//set for 2 digits after decimal place
55          form.setGroupingUsed(false);//no comma for thousands
56          form.setMinimumIntegerDigits(1);//leading 0 if < 1
57  
58          try {
59              return form.format((Double.valueOf(dValue)).doubleValue());
60          } catch (Exception execp) {
61               return dValue;
62          }
63      }
64  }