예제 #1
0
  public void testToString() throws Exception {

    DecimalFormatSymbols symbols = new DecimalFormatSymbols();

    DvQuantity q = new DvQuantity("kg", 78, 2, ms);
    String expected = "78" + symbols.getDecimalSeparator() + "00 kg";
    assertEquals(expected, q.toString());

    q = new DvQuantity("kg", 78, ms);
    expected = "78 kg";
    assertEquals(expected, q.toString());

    q = new DvQuantity(78);
    expected = "78";
    assertEquals(expected, q.toString());

    q = new DvQuantity(78.9);
    expected = "79";
    assertEquals(expected, q.toString());

    q = new DvQuantity(78.5);
    expected = "78";
    assertEquals(expected, q.toString());

    q = new DvQuantity(78.5, 3, ms);
    expected = "78" + symbols.getDecimalSeparator() + "500";
    assertEquals(expected, q.toString());
  }
예제 #2
0
파일: UIUtils.java 프로젝트: ralic/dbeaver
 public static VerifyListener getNumberVerifyListener(Locale locale) {
   DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
   final char[] allowedChars =
       new char[] {
         symbols.getDecimalSeparator(),
         symbols.getGroupingSeparator(),
         symbols.getMinusSign(),
         symbols.getZeroDigit(),
         symbols.getMonetaryDecimalSeparator(),
         '+'
       };
   final String exponentSeparator = symbols.getExponentSeparator();
   return new VerifyListener() {
     @Override
     public void verifyText(VerifyEvent e) {
       for (int i = 0; i < e.text.length(); i++) {
         char ch = e.text.charAt(i);
         if (!Character.isDigit(ch)
             && !ArrayUtils.contains(allowedChars, ch)
             && exponentSeparator.indexOf(ch) == -1) {
           e.doit = false;
           return;
         }
       }
       e.doit = true;
     }
   };
 }
예제 #3
0
 /**
  * Returns true if Decimal Point (not comma)
  *
  * @return use of decimal point
  */
 public boolean isDecimalPoint() {
   if (m_decimalPoint == null) {
     DecimalFormatSymbols dfs = new DecimalFormatSymbols(m_locale);
     m_decimalPoint = new Boolean(dfs.getDecimalSeparator() == '.');
   }
   return m_decimalPoint.booleanValue();
 } //  isDecimalPoint
예제 #4
0
  private static void describeDecimalFormatSymbols(StringBuilder result, DecimalFormatSymbols dfs) {
    result.append("Currency Symbol: " + unicodeString(dfs.getCurrencySymbol()) + "\n");
    result.append(
        "International Currency Symbol: "
            + unicodeString(dfs.getInternationalCurrencySymbol())
            + "\n");
    result.append("<p>");

    result.append("Digit: " + unicodeString(dfs.getDigit()) + "\n");
    result.append("Pattern Separator: " + unicodeString(dfs.getPatternSeparator()) + "\n");
    result.append("<p>");

    result.append("Decimal Separator: " + unicodeString(dfs.getDecimalSeparator()) + "\n");
    result.append(
        "Monetary Decimal Separator: " + unicodeString(dfs.getMonetaryDecimalSeparator()) + "\n");
    // 1.6: result.append("Exponent Separator: " + dfs.getExponentSeparator() + "\n");
    result.append("Grouping Separator: " + unicodeString(dfs.getGroupingSeparator()) + "\n");

    result.append("Infinity: " + unicodeString(dfs.getInfinity()) + "\n");
    result.append("Minus Sign: " + unicodeString(dfs.getMinusSign()) + "\n");
    result.append("NaN: " + unicodeString(dfs.getNaN()) + "\n");
    result.append("Percent: " + unicodeString(dfs.getPercent()) + "\n");
    result.append("Per Mille: " + unicodeString(dfs.getPerMill()) + "\n");
    result.append("Zero Digit: " + unicodeString(dfs.getZeroDigit()) + "\n");
    StringBuilder digits = new StringBuilder();
    for (int i = 0; i <= 9; ++i) {
      digits.append((char) (dfs.getZeroDigit() + i));
    }
    result.append("Digits: " + digits.toString() + "\n");
    result.append("<p>");
    result.append("<p>");
  }
 static void assertDecimalFormatSymbolsRIFrance(DecimalFormatSymbols dfs) {
   // Values based on Java 1.5 RI DecimalFormatSymbols for Locale.FRANCE
   /*
    * currency = [EUR]
    * currencySymbol = [€][U+20ac]
    * decimalSeparator = [,][U+002c]
    * digit = [#][U+0023]
    * groupingSeparator = [ ][U+00a0]
    * infinity = [∞][U+221e]
    * internationalCurrencySymbol = [EUR]
    * minusSign = [-][U+002d]
    * monetaryDecimalSeparator = [,][U+002c]
    * naN = [�][U+fffd]
    * patternSeparator = [;][U+003b]
    * perMill = [‰][U+2030]
    * percent = [%][U+0025]
    * zeroDigit = [0][U+0030]
    */
   assertEquals("EUR", dfs.getCurrency().getCurrencyCode());
   assertEquals("\u20AC", dfs.getCurrencySymbol());
   assertEquals(',', dfs.getDecimalSeparator());
   assertEquals('#', dfs.getDigit());
   assertEquals('\u00a0', dfs.getGroupingSeparator());
   assertEquals("\u221e", dfs.getInfinity());
   assertEquals("EUR", dfs.getInternationalCurrencySymbol());
   assertEquals('-', dfs.getMinusSign());
   assertEquals(',', dfs.getMonetaryDecimalSeparator());
   // RI's default NaN is U+FFFD, Harmony's is based on ICU
   assertEquals("\uFFFD", dfs.getNaN());
   assertEquals('\u003b', dfs.getPatternSeparator());
   assertEquals('\u2030', dfs.getPerMill());
   assertEquals('%', dfs.getPercent());
   assertEquals('0', dfs.getZeroDigit());
 }
예제 #6
0
 String defaultValue() {
   DecimalFormatSymbols symbols = ((DecimalFormat) numberFormat).getDecimalFormatSymbols();
   if (symbols.getDecimalSeparator() == '.') {
     return "0.0";
   } else {
     return "0,0";
   }
 }
예제 #7
0
  protected double getDoubleValue() {
    String sVal = elem.getValue();
    String sDecSep = elem.getSeparatorValue(MessageElement.SP_DECIMAL);
    if (sDecSep.length() == 0) return Double.valueOf(sVal).doubleValue();

    DecimalFormatSymbols dec = new DecimalFormatSymbols();
    if (sDecSep.length() == 1 && sDecSep.charAt(0) == dec.getDecimalSeparator())
      return Double.valueOf(sVal).doubleValue();

    int nIndex = sVal.indexOf(sDecSep);
    if (nIndex < 0) return Double.valueOf(sVal).floatValue();

    StringBuffer buf = new StringBuffer(sVal);
    buf.replace(
        nIndex, nIndex + sDecSep.length(), new Character(dec.getDecimalSeparator()).toString());
    return Double.valueOf(buf.toString()).doubleValue();
  }
 /** @tests java.text.DecimalFormatSymbols#setDecimalSeparator(char) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "setDecimalSeparator",
     args = {char.class})
 public void test_setDecimalSeparatorC() {
   dfs.setDecimalSeparator('*');
   assertEquals("Returned incorrect DecimalSeparator symbol", '*', dfs.getDecimalSeparator());
 }
예제 #9
0
 protected void setDoubleValue(double d) {
   String sVal = Double.toString(d);
   String sDecSep = elem.getSeparatorValue(MessageElement.SP_DECIMAL);
   if (sDecSep.length() == 0) elem.setValue(sVal);
   else {
     DecimalFormatSymbols dec = new DecimalFormatSymbols();
     if (sDecSep.length() == 1 && sDecSep.charAt(0) == dec.getDecimalSeparator())
       elem.setValue(sVal);
     else {
       int nIndex = sVal.indexOf(dec.getDecimalSeparator());
       if (nIndex < 0) elem.setValue(sVal);
       else {
         StringBuffer buf = new StringBuffer(sVal);
         buf.replace(nIndex, nIndex + 1, sDecSep);
         elem.setValue(new String(buf));
       }
     }
   }
 }
예제 #10
0
 /**
  * Constructor
  *
  * @param displayType
  * @param format
  * @param tc
  * @param title
  */
 public MDocNumber(int displayType, DecimalFormat format, JTextComponent tc, String title) {
   super();
   if (format == null || tc == null || title == null)
     throw new IllegalArgumentException("Invalid argument");
   //
   m_displayType = displayType;
   m_format = format;
   m_tc = tc;
   m_title = title;
   //
   DecimalFormatSymbols sym = m_format.getDecimalFormatSymbols();
   m_decimalSeparator = sym.getDecimalSeparator();
   m_groupingSeparator = sym.getGroupingSeparator();
   m_minusSign = sym.getMinusSign();
   //	log.finest("Decimal=" + m_decimalSeparator + "(" + (int)m_decimalSeparator
   //		+ ") - Group=" + m_groupingSeparator + "(" + (int)m_groupingSeparator +")");
 } //	MDocNumber
예제 #11
0
 /**
  * 数値の文字列での表記をグルーピングセパレータを削除し、小数点を.であらわした標準形に正規化します。
  *
  * @param s
  * @param locale
  * @return 正規化された文字列
  */
 public static String normalize(String s, Locale locale) {
   if (s == null) {
     return null;
   }
   DecimalFormatSymbols symbols = DecimalFormatSymbolsUtil.getDecimalFormatSymbols(locale);
   char decimalSep = symbols.getDecimalSeparator();
   char groupingSep = symbols.getGroupingSeparator();
   StringBuffer buf = new StringBuffer(20);
   for (int i = 0; i < s.length(); ++i) {
     char c = s.charAt(i);
     if (c == groupingSep) {
       continue;
     } else if (c == decimalSep) {
       c = '.';
     }
     buf.append(c);
   }
   return buf.toString();
 }
  public boolean isStringNumeric(String str) {
    DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance();
    char localeMinusSign = currentLocaleSymbols.getMinusSign();

    if (!Character.isDigit(str.charAt(0)) && str.charAt(0) != localeMinusSign) return false;

    boolean isDecimalSeparatorFound = false;
    char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator();

    for (char c : str.substring(1).toCharArray()) {
      if (!Character.isDigit(c)) {
        if (c == localeDecimalSeparator && !isDecimalSeparatorFound) {
          isDecimalSeparatorFound = true;
          continue;
        }
        return false;
      }
    }

    return true;
  }
예제 #13
0
  private static DateTimeFormatSymbols createInfo(Locale locale) {
    DecimalFormatSymbols oldSymbols = DecimalFormatSymbols.getInstance(locale);
    DateTimeFormatter.checkNotNull(oldSymbols, "Symbols to convert must not be null");
    char zeroDigit = oldSymbols.getZeroDigit();
    char positiveSign = '+';
    char negativeSign = oldSymbols.getMinusSign();
    char decimalSeparator = oldSymbols.getDecimalSeparator();

    Calendar cal = Calendar.getInstance(locale);
    int calFDoW = cal.getFirstDayOfWeek();
    DayOfWeek firstDayOfWeek = (calFDoW == 1 ? DayOfWeek.SUNDAY : DayOfWeek.of(calFDoW - 1));
    int minDaysInFirstWeek = cal.getMinimalDaysInFirstWeek();

    return new DateTimeFormatSymbols(
        locale,
        zeroDigit,
        positiveSign,
        negativeSign,
        decimalSeparator,
        firstDayOfWeek,
        minDaysInFirstWeek);
  }
예제 #14
0
  public void guessType() {
    nf = NumberFormat.getInstance();
    df = (DecimalFormat) nf;
    dfs = new DecimalFormatSymbols();
    daf = new SimpleDateFormat();

    daf.setLenient(false);

    // Start with a string...
    type = ValueMetaInterface.TYPE_STRING;

    // If we have no samples, we assume a String...
    if (samples == null) return;

    //////////////////////////////
    // DATES
    //////////////////////////////

    // See if all samples can be transformed into a date...
    int datefmt_cnt = date_formats.length;
    boolean datefmt[] = new boolean[date_formats.length];
    for (int i = 0; i < date_formats.length; i++) {
      datefmt[i] = true;
    }
    int datenul = 0;

    for (int i = 0; i < samples.length; i++) {
      if (samples[i].length() > 0 && samples[i].equalsIgnoreCase(nullString)) {
        datenul++;
      } else
        for (int x = 0; x < date_formats.length; x++) {
          if (samples[i] == null || Const.onlySpaces(samples[i]) || samples[i].length() == 0) {
            datefmt[x] = false;
            datefmt_cnt--;
          }

          if (datefmt[x]) {
            try {
              daf.applyPattern(date_formats[x]);
              Date date = daf.parse(samples[i]);

              Calendar cal = Calendar.getInstance();
              cal.setTime(date);
              int year = cal.get(Calendar.YEAR);

              if (year < 1800 || year > 2200) {
                datefmt[x] = false; // Don't try it again in the future.
                datefmt_cnt--; // One less that works..
              }
            } catch (Exception e) {
              datefmt[x] = false; // Don't try it again in the future.
              datefmt_cnt--; // One less that works..
            }
          }
        }
    }

    // If it is a date, copy info over to the format etc. Then return with the info.
    // If all samples where NULL values, we can't really decide what the type is.
    // So we're certainly not going to take a date, just take a string in that case.
    if (datefmt_cnt > 0 && datenul != samples.length) {
      int first = -1;
      for (int i = 0; i < date_formats.length && first < 0; i++) {
        if (datefmt[i]) first = i;
      }

      type = ValueMetaInterface.TYPE_DATE;
      format = date_formats[first];

      return;
    }

    //////////////////////////////
    // NUMBERS
    //////////////////////////////

    boolean isnumber = true;

    // Set decimal symbols to default
    decimalSymbol = "" + dfs.getDecimalSeparator();
    groupSymbol = "" + dfs.getGroupingSeparator();

    boolean numfmt[] = new boolean[number_formats.length];
    int maxprecision[] = new int[number_formats.length];
    for (int i = 0; i < numfmt.length; i++) {
      numfmt[i] = true;
      maxprecision[i] = -1;
    }
    int numfmt_cnt = number_formats.length;
    int numnul = 0;

    for (int i = 0; i < samples.length && isnumber; i++) {
      boolean contains_dot = false;
      boolean contains_comma = false;

      String field = samples[i];

      if (field.length() > 0 && field.equalsIgnoreCase(nullString)) {
        numnul++;
      } else {
        for (int x = 0; x < field.length() && isnumber; x++) {
          char ch = field.charAt(x);
          if (!Character.isDigit(ch)
              && ch != '.'
              && ch != ','
              && (ch != '-' || x > 0)
              && ch != 'E'
              && ch != 'e' // exponential
          ) {
            isnumber = false;
            numfmt_cnt = 0;
          } else {
            if (ch == '.') {
              contains_dot = true;
              // containsDot  = true;
            }
            if (ch == ',') {
              contains_comma = true;
              // containsComma  = true;
            }
          }
        }
        // If it's still a number, try to parse it as a double
        if (isnumber) {
          if (contains_dot && !contains_comma) // American style 174.5
          {
            dfs.setDecimalSeparator('.');
            decimalSymbol = ".";
            dfs.setGroupingSeparator(',');
            groupSymbol = ",";
          } else if (!contains_dot && contains_comma) // European style 174,5
          {
            dfs.setDecimalSeparator(',');
            decimalSymbol = ",";
            dfs.setGroupingSeparator('.');
            groupSymbol = ".";
          } else if (contains_dot && contains_comma) // Both appear!
          {
            // What's the last occurance: decimal point!
            int idx_dot = field.indexOf('.');
            int idx_com = field.indexOf(',');
            if (idx_dot > idx_com) {
              dfs.setDecimalSeparator('.');
              decimalSymbol = ".";
              dfs.setGroupingSeparator(',');
              groupSymbol = ",";
            } else {
              dfs.setDecimalSeparator(',');
              decimalSymbol = ",";
              dfs.setGroupingSeparator('.');
              groupSymbol = ".";
            }
          }

          // Try the remaining possible number formats!
          for (int x = 0; x < number_formats.length; x++) {
            if (numfmt[x]) {
              boolean islong = true;

              try {
                int prec = -1;
                // Try long integers first....
                if (!contains_dot && !contains_comma) {
                  try {
                    Long.parseLong(field);
                    prec = 0;
                  } catch (Exception e) {
                    islong = false;
                  }
                }

                if (!islong) // Try the double
                {
                  df.setDecimalFormatSymbols(dfs);
                  df.applyPattern(number_formats[x]);

                  double d = df.parse(field).doubleValue();
                  prec = guessPrecision(d);
                }
                if (prec > maxprecision[x]) maxprecision[x] = prec;
              } catch (Exception e) {
                numfmt[x] = false; // Don't try it again in the future.
                numfmt_cnt--; // One less that works..
              }
            }
          }
        }
      }
    }

    // Still a number?  Grab the result and return.
    // If all sample strings are empty or represent NULL values we can't take a number as type.
    if (numfmt_cnt > 0 && numnul != samples.length) {
      int first = -1;
      for (int i = 0; i < number_formats.length && first < 0; i++) {
        if (numfmt[i]) first = i;
      }

      type = ValueMetaInterface.TYPE_NUMBER;
      format = number_formats[first];
      precision = maxprecision[first];

      // Wait a minute!!! What about Integers?
      // OK, only if the precision is 0 and the length <19 (java long integer)
      /*
      if (length<19 && precision==0 && !containsDot && !containsComma)
      {
      	type=ValueMetaInterface.TYPE_INTEGER;
      	decimalSymbol="";
      	groupSymbol="";
      }
               */

      return;
    }

    //
    // Assume it's a string...
    //
    type = ValueMetaInterface.TYPE_STRING;
    format = "";
    precision = -1;
    decimalSymbol = "";
    groupSymbol = "";
    currencySymbol = "";
  }
예제 #15
0
 public KiloFormatter(int base, Locale locale) {
   this.base = base;
   DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
   this.decimalSeparator = symbols.getDecimalSeparator();
 }
public class SimpleCalculatorViewController implements ISimpleCalculatorViewController {

  // ... constants

  private static final String MINUS = "-";
  private static final String ZERO = BigDecimal.ZERO.toString();

  // ... configuration properties

  final Locale locale = Locale.US;

  final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
  final String decimalSeparator = "" + symbols.getDecimalSeparator();
  final String groupSeparator = "" + symbols.getGroupingSeparator();

  // ... controller state properties

  BigDecimal arg1;
  String currentArgumentInput;
  boolean currentArgumentInputFinished;

  EMathOperation selectedOperation;

  // ... constructor

  public SimpleCalculatorViewController() {

    init();
  }

  public void init() {

    resetCurrentArgumentInput();

    selectedOperation = null;
  }

  public SimpleCalculatorFacade getSimpleCalculatorFacade() {

    final SimpleCalculatorFacade simpleCalculatorFacade = new SimpleCalculatorFacade();
    return simpleCalculatorFacade;
  }

  // ... view data access

  @Override
  public String getDisplayValue() {

    return currentArgumentInput;
  }

  @Override
  public String getDecimalSeparator() {

    return decimalSeparator;
  }

  // ... business methods

  @Override
  public void calculate() {

    if (selectedOperation == null) {

      // ... nothing to do: insufficient data for calculation.
    } else {

      final BigDecimal result;

      final BigDecimal arg2 = BigDecimalUtils.stringToBigDecimal(currentArgumentInput, locale);

      if (selectedOperation.isUnary()) {

        result = getSimpleCalculatorFacade().calculate(arg2, selectedOperation);
      } else {
        result = getSimpleCalculatorFacade().calculate(arg1, arg2, selectedOperation);
      }

      selectedOperation = null;

      currentArgumentInput = BigDecimalUtils.bigDecimalToString(result, locale);
      currentArgumentInputFinished = true;
    }
  }

  @Override
  public void cancelInput() {

    resetCurrentArgumentInput();
  }

  @Override
  public void deleteLastInputSign() {

    resetCurrentArgumentInput_If_It_Was_Finished();

    final int currentArgumentLength = currentArgumentInput.length();

    if (currentArgumentLength == 1) {

      currentArgumentInput = ZERO;
    }
    if (currentArgumentLength == 2 && currentArgumentInput.startsWith(MINUS)) {

      currentArgumentInput = ZERO;
    }
    if (currentArgumentLength > 1) {

      currentArgumentInput = currentArgumentInput.substring(0, currentArgumentLength - 1);
    }
  }

  @Override
  public void putInCommaSign() {

    resetCurrentArgumentInput_If_It_Was_Finished();

    if (currentArgumentInput.contains(decimalSeparator)) {

      // ... nothing to do: there is already a comma.
    } else {
      currentArgumentInput += decimalSeparator;
    }
  }

  @Override
  public void putInDigitSign(final byte number) {

    resetCurrentArgumentInput_If_It_Was_Finished();

    if (currentArgumentInput.equals(ZERO)) {

      currentArgumentInput = "" + number;
    } else {
      currentArgumentInput += number;
    }
  }

  private void resetCurrentArgumentInput() {

    currentArgumentInput = ZERO;
    currentArgumentInputFinished = false;
  }

  private void resetCurrentArgumentInput_If_It_Was_Finished() {

    if (currentArgumentInputFinished) {

      resetCurrentArgumentInput();
    }
  }

  @Override
  public void selectMathOperation(final EMathOperation mathOperation) {

    selectedOperation = mathOperation;

    arg1 = BigDecimalUtils.stringToBigDecimal(currentArgumentInput, locale);
    currentArgumentInputFinished = true;

    if (mathOperation.isUnary()) {

      calculate();
    }
  }
}
 @Override
 public String getHint() {
   return "123" + decimalFormatSymbols.getDecimalSeparator() + "45 ";
 }