Java Code Examples for java.text.DecimalFormatSymbols

The following examples show how to use java.text.DecimalFormatSymbols. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: pentaho-kettle   Source File: LDIFInputData.java    License: Apache License 2.0 6 votes vote down vote up
public LDIFInputData() {
  super();
  nrInputFields = -1;
  thisline = null;
  nextline = null;
  nf = NumberFormat.getInstance();
  df = (DecimalFormat) nf;
  dfs = new DecimalFormatSymbols();
  daf = new SimpleDateFormat();
  dafs = new DateFormatSymbols();

  nr_repeats = 0;
  filenr = 0;

  fr = null;
  zi = null;
  is = null;
  InputLDIF = null;
  recordLDIF = null;
  multiValueSeparator = ",";
  totalpreviousfields = 0;
  readrow = null;
  indexOfFilenameField = -1;
}
 
Example 2
@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);

    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";

        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }

        log.debug(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len + throughput
                + ")");
    }
}
 
Example 3
private void showBalance() {
    networkManager.getBalance(walletManager.getWalletFriendlyAddress(), new Callback<BigDecimal>() {
        @Override
        public void onResponse(BigDecimal balance) {
            DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
            symbols.setDecimalSeparator('.');
            symbols.setGroupingSeparator(',');
            DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols);
            decimalFormat.setRoundingMode(RoundingMode.DOWN);
            if (balance != null && !balance.equals(new BigDecimal(0))) {
                curBalance = decimalFormat.format(balance);
                setCryptoBalance(curBalance);
                getLocalBalance(curBalance);
            }
        }
    });
}
 
Example 4
Source Project: furnace   Source File: LogTransferListener.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void transferSucceeded(TransferEvent event)
{
   transferCompleted(event);
   TransferResource resource = event.getResource();
   long contentLength = event.getTransferredBytes();
   if (contentLength >= 0)
   {
      String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
      String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";

      String throughput = "";
      long duration = System.currentTimeMillis() - resource.getTransferStartTime();
      if (duration > 0)
      {
         DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
         double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
         throughput = " at " + format.format(kbPerSec) + " KB/sec";
      }

      out.println(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len
               + throughput + ")");
   }
}
 
Example 5
private void updateArrivalField() {
    if (amountToSend == null) return;
    if (isInclude) {
        BigDecimal amountDecimal = new BigDecimal(amountToSend);
        BigDecimal arrivalAmountDecimal = amountDecimal.subtract(currentFeeEth);
        if (arrivalAmountDecimal.compareTo(BigDecimal.ZERO) < 0) {
            arrivalAmountDecimal = BigDecimal.ZERO;
        }
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
        symbols.setDecimalSeparator('.');
        DecimalFormat decimalFormat = new DecimalFormat("###0.########", symbols);
        arrivalAmountToSend = decimalFormat.format(arrivalAmountDecimal);
        etArrivalAmount.setText(arrivalAmountToSend);
    } else {
        etArrivalAmount.setText(amountToSend);
    }
}
 
Example 6
@Override
public void setPrimaryValue(String tmpVal) {
       double tmpNum=0;
       if(this.primaryOperator==TargetNode.OPERATOR_IS.getOperatorCode()) {
           if(!tmpVal.equals("null") && !tmpVal.equals("not null")) {
               this.primaryValue = "null";
           } else {
               this.primaryValue=tmpVal;
           }
       } else {
           try {
               tmpNum=Double.parseDouble(tmpVal);
           } catch (Exception e) {
               if (logger.isInfoEnabled()) logger.info("Error in Number-Parsing: "+e);
           }
           DecimalFormat aFormat=new DecimalFormat("0.###########", new DecimalFormatSymbols(Locale.US));
           this.primaryValue=aFormat.format(tmpNum);
           // this.primaryValue=NumberFormat.getInstance(Locale.US).format(tmpNum);
           // this.primaryValue=Double.toString(tmpNum);
       }
   }
 
Example 7
Source Project: lucene-solr   Source File: TestRegexpRandom.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  dir = newDirectory();
  RandomIndexWriter writer = new RandomIndexWriter(random(), dir,
      newIndexWriterConfig(new MockAnalyzer(random()))
      .setMaxBufferedDocs(TestUtil.nextInt(random(), 50, 1000)));
  
  Document doc = new Document();
  FieldType customType = new FieldType(TextField.TYPE_STORED);
  customType.setOmitNorms(true);
  Field field = newField("field", "", customType);
  doc.add(field);
  
  NumberFormat df = new DecimalFormat("000", new DecimalFormatSymbols(Locale.ROOT));
  for (int i = 0; i < 1000; i++) {
    field.setStringValue(df.format(i));
    writer.addDocument(doc);
  }
  
  reader = writer.getReader();
  writer.close();
  searcher = newSearcher(reader);
}
 
Example 8
public void testParseDoubleNonRootLocale() throws Exception {
  final DecimalFormatSymbols fr_FR = DecimalFormatSymbols.getInstance(new Locale("fr","FR"));
  final char groupChar = fr_FR.getGroupingSeparator();
  final char decimalChar = fr_FR.getDecimalSeparator();

  double value = 10898.83491D;
  String doubleString1 = "10898"+decimalChar+"83491";
  String doubleString2 = "10"+groupChar+"898"+decimalChar+"83491";
  
  IndexSchema schema = h.getCore().getLatestSchema();
  assertNotNull(schema.getFieldOrNull("double_d")); // should match dynamic field "*_d"
  assertNull(schema.getFieldOrNull("not_in_schema"));
  SolrInputDocument d = processAdd("parse-double-french-no-run-processor",
                                   doc(f("id", "140"), f("double_d", doubleString1), 
                                       f("not_in_schema", doubleString2)));
  assertNotNull(d);
  assertThat(d.getFieldValue("double_d"), IS_DOUBLE);
  assertEquals(value, (Double)d.getFieldValue("double_d"), EPSILON);
  assertThat(d.getFieldValue("not_in_schema"), IS_DOUBLE);
  assertEquals(value, (Double)d.getFieldValue("not_in_schema"), EPSILON);
}
 
Example 9
Source Project: hop   Source File: AddXmlData.java    License: Apache License 2.0 6 votes vote down vote up
/**
   *
   */
public AddXmlData() {
  super();

  nf = NumberFormat.getInstance();
  df = (DecimalFormat) nf;
  dfs = new DecimalFormatSymbols();

  defaultDecimalFormat = (DecimalFormat) NumberFormat.getInstance();
  defaultDecimalFormatSymbols = new DecimalFormatSymbols();

  daf = new SimpleDateFormat();
  dafs = new DateFormatSymbols();

  defaultDateFormat = new SimpleDateFormat();
  defaultDateFormatSymbols = new DateFormatSymbols();

}
 
Example 10
@Override
public void transferSucceeded( TransferEvent event )
{
    transferCompleted( event );

    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if ( contentLength >= 0 )
    {
        String type = ( event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded" );
        String len = contentLength >= 1024 ? toKB( contentLength ) + " KB" : contentLength + " B";

        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if ( duration > 0 )
        {
            long bytes = contentLength - resource.getResumeOffset();
            DecimalFormat format = new DecimalFormat( "0.0", new DecimalFormatSymbols( Locale.ENGLISH ) );
            double kbPerSec = ( bytes / 1024.0 ) / ( duration / 1000.0 );
            throughput = " at " + format.format( kbPerSec ) + " KB/sec";
        }

        logger.info( type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len
            + throughput + ")" );
    }
}
 
Example 11
private void updateEthBalance() {
    btnSend.setEnabled(false);
    mNetwonetworkManagerkManager.getBalance(walletManager.getWalletFriendlyAddress(), new Callback<BigDecimal>() {
        @Override
        public void onResponse(BigDecimal response) {
            btnSend.setEnabled(true);
            balance = response;
            DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
            symbols.setDecimalSeparator('.');
            symbols.setGroupingSeparator(',');
            DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols);
            decimalFormat.setRoundingMode(RoundingMode.DOWN);
            if (balance != null && !balance.equals(new BigDecimal(0))) {
                setCurrentBalance(decimalFormat.format(balance), sharedManager.getCurrentCurrency().toUpperCase());
            }
        }
    });
}
 
Example 12
private NumberFormat getInstance(Locale locale,
                                        int choice) {
    if (locale == null) {
        throw new NullPointerException();
    }

    LocaleProviderAdapter adapter = LocaleProviderAdapter.forType(type);
    String[] numberPatterns = adapter.getLocaleResources(locale).getNumberPatterns();
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
    int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
    DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

    if (choice == INTEGERSTYLE) {
        format.setMaximumFractionDigits(0);
        format.setDecimalSeparatorAlwaysShown(false);
        format.setParseIntegerOnly(true);
    } else if (choice == CURRENCYSTYLE) {
        adjustForCurrencyDefaultFractionDigits(format, symbols);
    }

    return format;
}
 
Example 13
Source Project: arx   Source File: SWTUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a pretty string representing the given double
 * @param value
 * @return
 */
public static String getPrettyString(double value) {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
    if (value == LN2) {
        return "ln(2)";
    } else if (value == LN3) {
        return "ln(3)";
    } else if (value == 0) {
        return "0";
    } else if (Math.abs(value) < 0.00001) {
        return new DecimalFormat("#.#####E0", symbols).format(value).replace('E', 'e');
    } else if (Math.abs(value) < 1) {
        return new DecimalFormat("#.#####", symbols).format(value);
    } else if (Math.abs(value) < 100000) {
        return new DecimalFormat("######.#####", symbols).format(value);
    } else {
        return String.valueOf(value).replace('E', 'e');
    }
}
 
Example 14
Source Project: jsr354-ri   Source File: AmountNumberTokenTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParse_FR_with_NBSP_and_preset_decimal_symbols() {
    DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(FRANCE);
    DecimalFormatSymbols syms = decimalFormat.getDecimalFormatSymbols();
    syms.setGroupingSeparator('\u00A0');

    testParse(FRANCE, PATTERN, syms, "12\u00A0345", 6, "int thousands", 12345.0, "12 345");
    testParse(FRANCE, PATTERN, syms, "-12\u00A0345", 7, "int thousands negative", -12345.0, "-12 345");
    testParse(FRANCE, PATTERN, syms, "12\u00A0345,6", 8, "float 1 thousands", 12345.6, "12 345,6");
    testParse(FRANCE, PATTERN, syms, "12\u00A0345,67", 9, "float 2 thousands", 12345.67, "12 345,67");
    testParse(FRANCE, PATTERN, syms, "12\u00A0345,678", 10, "float 3 thousands", 12345.678, "12 345,678");
    testParse(FRANCE, PATTERN, syms, "-12\u00A0345,6", 9, "float 1 thousands negative", -12345.6, "-12 345,6");
    testParse(FRANCE, PATTERN, syms, "-12\u00A0345,67", 10, "float 2 thousands negative", -12345.67, "-12 345,67");
    testParse(FRANCE, PATTERN, syms, "-12\u00A0345,678", 11, "float 3 thousands negative", -12345.678, "-12 345,678");
    testParse(FRANCE, PATTERN, syms, "-1\u00A0234\u00A0567,89", 13, "float 2 million negative", -1234567.89, "-1 234 567,89");
    testParse(FRANCE, PATTERN, syms, "\u00A0-1\u00A0234\u00A0567,89", 14, "float 2 million negative with leading space", -1234567.89, " -1 234 567,89");
    testParse(FRANCE, PATTERN, syms, "\u00A0-1\u00A0234\u00A0567,89\u00A0", 14, "float 2 million negative with leading and trailing space", -1234567.89, " -1 234 567,89 ");
}
 
Example 15
private void printTestInfo(int maxCacheSize) {

        DecimalFormat grouped = new DecimalFormat("000,000");
        DecimalFormatSymbols formatSymbols = grouped.getDecimalFormatSymbols();
        formatSymbols.setGroupingSeparator(' ');
        grouped.setDecimalFormatSymbols(formatSymbols);

        System.out.format(
                "Test will use %s bytes of memory of %s available%n"
                + "Available memory is %s with %d bytes pointer size - can save %s pointers%n"
                + "Max cache size: 2^%d = %s elements%n",
                grouped.format(ShrinkAuxiliaryDataTest.getMemoryUsedByTest()),
                grouped.format(Runtime.getRuntime().maxMemory()),
                grouped.format(Runtime.getRuntime().maxMemory()
                        - ShrinkAuxiliaryDataTest.getMemoryUsedByTest()),
                Unsafe.ADDRESS_SIZE,
                grouped.format((Runtime.getRuntime().freeMemory()
                        - ShrinkAuxiliaryDataTest.getMemoryUsedByTest())
                        / Unsafe.ADDRESS_SIZE),
                maxCacheSize,
                grouped.format((int) Math.pow(2, maxCacheSize))
        );
    }
 
Example 16
Source Project: brein-time-utilities   Source File: NumberInterval.java    License: Apache License 2.0 6 votes vote down vote up
protected String unique(final double value) {
    if (MAX_DOUBLE < Math.abs(value)) {
        LOGGER.warn("Using double values larger than " + unique(MAX_DOUBLE));
    }

    if (value == Math.rint(value)) {
        return String.valueOf(Double.valueOf(value).longValue());
    } else {
        // http://stackoverflow.com/questions/16098046/
        // how-to-print-double-value-without-scientific-notation-using-java
        final DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMaximumFractionDigits(340);

        return df.format(value);
    }
}
 
Example 17
/**
 * Adjusts the minimum and maximum fraction digits to values that
 * are reasonable for the currency's default fraction digits.
 */
private static void adjustForCurrencyDefaultFractionDigits(
        DecimalFormat format, DecimalFormatSymbols symbols) {
    Currency currency = symbols.getCurrency();
    if (currency == null) {
        try {
            currency = Currency.getInstance(symbols.getInternationalCurrencySymbol());
        } catch (IllegalArgumentException e) {
        }
    }
    if (currency != null) {
        int digits = currency.getDefaultFractionDigits();
        if (digits != -1) {
            int oldMinDigits = format.getMinimumFractionDigits();
            // Common patterns are "#.##", "#.00", "#".
            // Try to adjust all of them in a reasonable way.
            if (oldMinDigits == format.getMaximumFractionDigits()) {
                format.setMinimumFractionDigits(digits);
                format.setMaximumFractionDigits(digits);
            } else {
                format.setMinimumFractionDigits(Math.min(digits, oldMinDigits));
                format.setMaximumFractionDigits(digits);
            }
        }
    }
}
 
Example 18
Source Project: ETSMobile-Android2   Source File: MyCourseDetailAdapter.java    License: Apache License 2.0 6 votes vote down vote up
public MyCourseDetailAdapter(final Context context, final ListeDesElementsEvaluation courseEvaluation, String cote) {
	super();
	this.courseEvaluation = courseEvaluation;
	this.cote = cote;
	nf_frCA = new DecimalFormat("##,#", new DecimalFormatSymbols(Locale.CANADA_FRENCH));
	nf_enUS = new DecimalFormat("##.#");
	// parse exams results
	for ( ElementEvaluation evaluationElement : courseEvaluation.liste) {
		if(evaluationElement.note !=null){
			if(evaluationElement.ignoreDuCalcul.equals("Non")){
				try {
					final String pond = evaluationElement.ponderation;
					final double value = nf_frCA.parse(pond).doubleValue();
					total += value;
					if(total>100){
						total = 100;
					}
				} catch (final ParseException e) {
				}
			}
		}
	}
	
	ctx = context;
	li = (LayoutInflater) ctx.getSystemService(inflater);
}
 
Example 19
public static String format(QualityGate.Condition condition) {
    Metric<?> metric = CoreMetrics.getMetric(condition.getMetricKey());
    if (metric.getType() == Metric.ValueType.RATING) {
        return String
                .format("%s %s (%s %s)", Rating.valueOf(Integer.parseInt(condition.getValue())), metric.getName(),
                        condition.getOperator() == QualityGate.Operator.GREATER_THAN ? "is worse than" :
                        "is better than", Rating.valueOf(Integer.parseInt(condition.getErrorThreshold())));
    } else if (metric.getType() == Metric.ValueType.PERCENT) {
        NumberFormat numberFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        return String.format("%s%% %s (%s %s%%)", numberFormat.format(new BigDecimal(condition.getValue())),
                             metric.getName(),
                             condition.getOperator() == QualityGate.Operator.GREATER_THAN ? "is greater than" :
                             "is less than", numberFormat.format(new BigDecimal(condition.getErrorThreshold())));
    } else {
        return String.format("%s %s (%s %s)", condition.getValue(), metric.getName(),
                             condition.getOperator() == QualityGate.Operator.GREATER_THAN ? "is greater than" :
                             "is less than", condition.getErrorThreshold());
    }
}
 
Example 20
Source Project: arcusandroid   Source File: RuleConversionUtils.java    License: Apache License 2.0 5 votes vote down vote up
public String getDurationForInfinity(String time) {
    try {
        return DecimalFormatSymbols.getInstance().getInfinity();
    }
    catch (Exception ex) {
        logger.debug("Caught ex trying to return infinity symbol.");
        return time;
    }
}
 
Example 21
Source Project: Strata   Source File: NumberFormatterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Disabled
public void test_javaBroken() throws Exception {
  // uncomment system out to see how broken it is
  // very specific format instance needed
  DecimalFormat format = new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH));
  Random random = new Random(1);
  CountDownLatch latch = new CountDownLatch(1);
  AtomicInteger broken = new AtomicInteger();
  int threadCount = 15;
  for (int i = 0; i < threadCount; i++) {
    Runnable runner = () -> {
      try {
        latch.await();
        int val = random.nextInt(999);
        String a = format.format((double) val);
        String b = Integer.valueOf(val).toString();
        System.out.println(a + " " + b);
        if (!a.equals(b)) {
          broken.incrementAndGet();
        }
      } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());
      }
    };
    new Thread(runner, "TestThread" + i).start();
  }
  // start all threads together
  latch.countDown();
  Thread.sleep(1000);
  System.out.println("Broken: " + broken.get());
  assertThat(broken.get() > 0).isTrue();
}
 
Example 22
@OnClick(R.id.btn_max)
public void maxAmount(View view) {
    if (balance != null && !balance.equals(new BigDecimal(0))) {
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();
        symbols.setDecimalSeparator('.');
        symbols.setGroupingSeparator(',');
        DecimalFormat decimalFormat = new DecimalFormat(ETH_SHOW_PATTERN, symbols);
        decimalFormat.setRoundingMode(RoundingMode.FLOOR);
        String clearAmount = decimalFormat.format(balance).replace(",","");
        etAmountToSend.setText(clearAmount);
        inputLayout.setCurrentText(clearAmount);
        etAmountToSend.setSelection(etAmountToSend.getText().length());
    }
}
 
Example 23
Source Project: ipst   Source File: FortranFormat.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public static DecimalFormat newDF_(String formatString) {
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
    return df;
}
 
Example 24
Source Project: nifi   Source File: ConvertExcelToCSVProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomDelimiters() throws Exception {
    testRunner.enqueue(new File("src/test/resources/dataformatting.xlsx").toPath());

    testRunner.setProperty(CSVUtils.VALUE_SEPARATOR, "|");
    testRunner.setProperty(CSVUtils.RECORD_SEPARATOR, "\\r\\n");
    testRunner.setProperty(ConvertExcelToCSVProcessor.FORMAT_VALUES, "true");

    testRunner.run();

    testRunner.assertTransferCount(ConvertExcelToCSVProcessor.SUCCESS, 1);
    testRunner.assertTransferCount(ConvertExcelToCSVProcessor.ORIGINAL, 1);
    testRunner.assertTransferCount(ConvertExcelToCSVProcessor.FAILURE, 0);

    MockFlowFile ff = testRunner.getFlowFilesForRelationship(ConvertExcelToCSVProcessor.SUCCESS).get(0);
    Long rowsSheet = new Long(ff.getAttribute(ConvertExcelToCSVProcessor.ROW_NUM));
    assertTrue(rowsSheet == 9);

    LocalDateTime localDt = LocalDateTime.of(2017, 1, 1, 12, 0, 0);
    DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
    String valueSeparator = testRunner.getProcessContext().getProperty(CSVUtils.VALUE_SEPARATOR).evaluateAttributeExpressions(ff).getValue();
    String decimalSeparator = (String.valueOf(decimalFormatSymbols.getDecimalSeparator()).equals(valueSeparator))
            ? ("\\" + decimalFormatSymbols.getDecimalSeparator()) : String.valueOf(decimalFormatSymbols.getDecimalSeparator());
    String groupingSeparator = String.valueOf(decimalFormatSymbols.getGroupingSeparator()).equals(valueSeparator)
            ? "\\" + decimalFormatSymbols.getGroupingSeparator() : String.valueOf(decimalFormatSymbols.getGroupingSeparator());
    ff.assertContentEquals(String.format("Numbers|Timestamps|Money\r\n" +
            "1234%1$s456|" + DateTimeFormatter.ofPattern("d/M/yy").format(localDt) + "|$   123%1$s45\r\n" +
            "1234%1$s46|" + DateTimeFormatter.ofPattern("hh:mm:ss a").format(localDt) + "|£   123%1$s45\r\n" +
            "1234%1$s5|" + DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy").format(localDt) + "|¥   123%1$s45\r\n" +
            "1%2$s234%1$s46|" + DateTimeFormatter.ofPattern("d/M/yy HH:mm").format(localDt) + "|$   1%2$s023%1$s45\r\n" +
            "1%2$s234%1$s4560|" + DateTimeFormatter.ofPattern("hh:mm a").format(localDt) + "|£   1%2$s023%1$s45\r\n" +
            "9%1$s88E+08|" + DateTimeFormatter.ofPattern("yyyy/MM/dd/ HH:mm").format(localDt) + "|¥   1%2$s023%1$s45\r\n" +
            "9%1$s877E+08||\r\n" +
            "9%1$s8765E+08||\r\n", decimalSeparator, groupingSeparator));
}
 
Example 25
/**
 * Regardless of the default locale, comma ('.') is used as decimal separator
 *
 * @param source
 * @return
 * @throws ParseException
 */
public BigDecimal parse(String source) throws ParseException {
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat("#.#", symbols);
    format.setParseBigDecimal(true);
    return (BigDecimal) format.parse(source);
}
 
Example 26
Source Project: javalite   Source File: ValidatorsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void testNumericValidator(){
        deleteAndPopulateTable("accounts");
        Account a = new Account();
        //try straight number
        a.set("amount", 1.2);
        a.validate();
        a(a.errors().size()).shouldBeEqual(0);

        //try not number
        a.set("amount", "hello");
        a.validate();
        a(a.errors().size()).shouldBeEqual(1);
        a(a.errors().get("amount")).shouldBeEqual("value is not a number");

        //try numeric string
        a.set("amount", "123");
        a.validate();
        a(a.errors().size()).shouldBeEqual(0);

        //try numeric string with decimal separator specific to actual Locale
        a.set("amount", "123" + DecimalFormatSymbols.getInstance().getDecimalSeparator() + "11");
        a.validate();
        a(a.errors().size()).shouldBeEqual(0);

        //try bad string with a number in it
        a.set("amount", "111 aaa");
        a.validate();
        a(a.errors().size()).shouldBeEqual(1);

//        //try null value with a validator.
//        a.set("amount", null);
//        a.validate();
//        a(a.errors().size()).shouldBeEqual(1);
//        a(a.errors().get("amount")).shouldBeEqual("value is not a number");
        
    }
 
Example 27
Source Project: bcm-android   Source File: MonetaryFormat.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Configure this instance with values from a {@link Locale}.
 */
public MonetaryFormat withLocale(Locale locale) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    char negativeSign = dfs.getMinusSign();
    char zeroDigit = dfs.getZeroDigit();
    char decimalMark = dfs.getMonetaryDecimalSeparator();
    return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
            shift, roundingMode, codes, codeSeparator, codePrefixed);
}
 
Example 28
Source Project: commons-jxpath   Source File: JXPathContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the named DecimalFormatSymbols.
 * @param name key
 * @return DecimalFormatSymbols
 * @see #setDecimalFormatSymbols(String, DecimalFormatSymbols)
 */
public synchronized DecimalFormatSymbols getDecimalFormatSymbols(String name) {
    if (decimalFormats == null) {
        return parentContext == null ? null : parentContext.getDecimalFormatSymbols(name);
    }
    return (DecimalFormatSymbols) decimalFormats.get(name);
}
 
Example 29
Source Project: ph-commons   Source File: RoundHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Source: http://www.luschny.de/java/doubleformat.html
 *
 * @param dValue
 *        the value to be formatted
 * @param nScale
 *        The precision of the decimal scale. If type is
 *        {@link EDecimalType#FIX} the decimal scale, else the (carrying scale
 *        - 1). Should be &ge; 0.
 * @param eType
 *        The formatting type. May not be <code>null</code>.
 * @param aLocale
 *        The locale to be used for the decimal symbols. May not be
 *        <code>null</code>.
 * @return the string representation of the double value. For NaN and infinite
 *         values, the return of {@link Double#toString()} is returned.
 */
@Nonnull
public static String getFormatted (final double dValue,
                                   @Nonnegative final int nScale,
                                   @Nonnull final EDecimalType eType,
                                   @Nonnull final Locale aLocale)
{
  ValueEnforcer.isGE0 (nScale, "Scale");
  ValueEnforcer.notNull (eType, "Type");
  ValueEnforcer.notNull (aLocale, "Locale");

  if (Double.isNaN (dValue) || Double.isInfinite (dValue))
    return Double.toString (dValue);

  // Avoid negative scales
  final DecimalFormat aDF = (DecimalFormat) NumberFormat.getInstance (aLocale);
  aDF.setDecimalFormatSymbols (DecimalFormatSymbols.getInstance (aLocale));
  aDF.setMaximumFractionDigits (nScale);
  aDF.setMinimumFractionDigits (nScale);

  if (eType.isExponential ())
  {
    String sPattern = "0E0";
    if (nScale > 0)
      sPattern += '.' + StringHelper.getRepeated ('0', nScale);
    aDF.applyPattern (sPattern);
  }
  else
  {
    aDF.setGroupingUsed (false);
    aDF.setMinimumIntegerDigits (1);
  }
  return aDF.format (dValue);
}
 
Example 30
Source Project: jdk8u-dev-jdk   Source File: Formatter.java    License: GNU General Public License v2.0 5 votes vote down vote up
private char getZero(Locale l) {
    if ((l != null) &&  !l.equals(locale())) {
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l);
        return dfs.getZeroDigit();
    }
    return zero;
}