Java Code Examples for java.text.NumberFormat.getInstance()

The following are Jave code examples for showing how to use getInstance() of the java.text.NumberFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: NotifyTools   File: StringLocaleConverter.java   View Source Code Vote up 6 votes
/**
 * Make an instance of DecimalFormat.
 *
 * @param locale The locale
 * @param pattern The pattern is used for the convertion
 * @return The format for the locale and pattern
 *
 * @throws ConversionException if conversion cannot be performed
 *  successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 */
private DecimalFormat getDecimalFormat(final Locale locale, final String pattern) {

    final DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale);

    // if some constructors default pattern to null, it makes only sense to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            numberFormat.applyLocalizedPattern(pattern);
        } else {
            numberFormat.applyPattern(pattern);
        }
    } else {
        log.debug("No pattern provided, using default.");
    }

    return numberFormat;
}
 
Example 2
Project: geomapapp   File: XMap.java   View Source Code Vote up 6 votes
public void setZoomHistoryNext(XMap mapSource) {
	Rectangle2D r = null;
	r = mapSource.getClipRect2D();
	Point2D.Double p2 = new Point2D.Double(
			r.getX()+.5*r.getWidth(),
			r.getY()+.5*r.getHeight() );
	p2 = (Point2D.Double)mapSource.getProjection().getRefXY(p2);

	double zoom = mapSource.getZoom();
	NumberFormat fmtZoom1 = NumberFormat.getInstance();
	fmtZoom1.setMinimumFractionDigits(1);
	fmtZoom1.format(zoom);

	nextZoom = "next, " + p2.getX() + ", " + p2.getY() + ", " + zoom;
	zoomActionTrack.selectAll();
	zoomActionTrack.replaceSelection(nextZoom);
	//System.out.println("track: " + zoomActionTrack.getText());
}
 
Example 3
Project: lams   File: NumberUtil.java   View Source Code Vote up 6 votes
/**
    * Convert a string back into a Float. Assumes string was formatted using formatLocalisedNumber originally. Should
    * ensure that it is using the same locale/number format as when it was formatted. If no locale is suppied, it will
    * use the server's locale.
    *
    * Need to strip out any spaces as spaces are valid group separators in some European locales (e.g. Polish) but they
    * seem to come back from Firefox as a plain space rather than the special separating space.
    */
   public static Double getLocalisedDouble(String inputStr, Locale locale) {
String numberStr = inputStr;
if (numberStr != null) {
    numberStr = numberStr.replace(" ", "");
}
if ((numberStr != null) && (numberStr.length() > 0)) {
    Locale useLocale = locale != null ? locale : NumberUtil.getServerLocale();
    NumberFormat format = NumberFormat.getInstance(useLocale);
    ParsePosition pp = new ParsePosition(0);
    Number num = format.parse(numberStr, pp);
    if ((num != null) && (pp.getIndex() == numberStr.length())) {
	return num.doubleValue();
    }
}
throw new NumberFormatException("Unable to convert number " + numberStr + "to double using locale "
	+ locale.getCountry() + " " + locale.getLanguage());
   }
 
Example 4
Project: oldmonk   File: ReporterAPI.java   View Source Code Vote up 6 votes
public String getSuccessPercentageForSuite()
{
    String successPercentageForSuite = "";

    NumberFormat nf = NumberFormat.getInstance();

    nf.setMaximumFractionDigits(2);
    nf.setGroupingUsed(true);

    try
    {
        successPercentageForSuite = nf
                .format(((float) getTotalPassedMethodsForSuite() / (float) (getTotalPassedMethodsForSuite()
                        + getTotalFailedMethodsForSuite() + getTotalSkippedMethodsForSuite())) * 100);
    } catch (NumberFormatException realCause)
    {
        LOGGER.debug(realCause.getMessage());
    }

    return successPercentageForSuite;
}
 
Example 5
Project: RunMap   File: FunctionFragPresenterImpl.java   View Source Code Vote up 6 votes
@Override
public void updateTotalDistance(Context context) {
    if(context != null){
        SharedPreferences sp = context.getSharedPreferences(RMConfiguration.FILE_CONFIG, Context.MODE_PRIVATE);
        long distance = sp.getLong(RMConfiguration.KEY_TOTAL_DISTANCE,0);
        long tmpDistance = sp.getLong(RMConfiguration.KEY_TMP_DISTANCE,0);
        if(tmpDistance < 0){
            return;
        }
        distance += tmpDistance;
        //if there have an effective value, update it now
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong(RMConfiguration.KEY_TMP_DISTANCE,0);
        editor.putLong(RMConfiguration.KEY_TOTAL_DISTANCE,distance);
        editor.commit();
        DecimalFormat distanceFormater = (DecimalFormat) NumberFormat.getInstance();
        distanceFormater.setMinimumFractionDigits(2);
        distanceFormater.setMaximumFractionDigits(2);
        mFunctionFragment.showUpgradeDistance(distanceFormater.format(distance/1000.0));
    }
}
 
Example 6
Project: RollenspielAlexaSkill   File: NumberUtil.java   View Source Code Vote up 5 votes
public static String num2decStr(double num, int digits) {
	NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
	nf.setMinimumFractionDigits(digits);
	nf.setMaximumFractionDigits(digits);
       String result = nf.format(num);		
	return result;
}
 
Example 7
Project: GitHub   File: BenchmarkExecutor.java   View Source Code Vote up 5 votes
public void handleResult(Codec codec, Result result) {
    if (result.getError() != null) {
        result.getError().printStackTrace();
        return;
    }
    NumberFormat format = NumberFormat.getInstance();
    System.out.println(result.getName() + "\t" + codec.getName() + "\t" + format.format(result.getMillis()) + "\tYGC " + result.getYoungGC()
                       + "\tYGCT " + result.getYoungGCTime());
}
 
Example 8
Project: Equella   File: NumberLabel.java   View Source Code Vote up 5 votes
@Override
public String getText()
{
	final NumberFormat numberFormat = NumberFormat.getInstance(CurrentLocale.getLocale());
	if( minDecimals != null )
	{
		numberFormat.setMinimumFractionDigits(minDecimals);
	}
	if( maxDecimals != null )
	{
		numberFormat.setMaximumFractionDigits(maxDecimals);
	}
	return numberFormat.format(number);
}
 
Example 9
Project: openjdk-jdk10   File: RoundingAndPropertyTest.java   View Source Code Vote up 5 votes
private static int testLocalizationValues() {

        DecimalFormat df = (DecimalFormat)
            NumberFormat.getInstance(GoldenDoubleValues.FullLocalizationTestLocale);

        double[] localizationValues = GoldenDoubleValues.DecimalLocalizationValues;
        int size = localizationValues.length;
        int successCounter = 0;
        int failureCounter = 0;
        for (int i = 0; i < size; i++) {

            double d = localizationValues[i];
            String formatted = df.format(d);

            char[] expectedUnicodeArray =
                getCharsFromUnicodeArray(
                    GoldenFormattedValues.DecimalDigitsLocalizedFormattedValues[i]);
            String expected = new String(expectedUnicodeArray);

            if (!formatted.equals(expected)) {
                failureCounter++;
                System.out.println(
                    "--- Localization error for value d = " + d +
                    ". Exact value = " + new BigDecimal(d).toString() +
                    ". Expected result = " + expected +
                    ". Output result = " + formatted);
            } else successCounter++;
        }
        System.out.println("Checked positively " + successCounter +
                           " golden decimal values out of " + size +
                           " tests. There were " + failureCounter +
                           " format failure");

        return failureCounter;
    }
 
Example 10
Project: onboarding-service   File: EstonianFeeFinderService.java   View Source Code Vote up 5 votes
private static float parseFee(String managementFee) throws ComparisonException, ParseException {
    float fee;
    if (managementFee.contains(",")){
        NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
        Number number = format.parse(managementFee);
        fee = number.floatValue()/100;
    }
    else {
        fee = Float.parseFloat(managementFee)/100;
    }
    if (fee > 0.02 || fee < 0) throw new FeeSizeException("Fee size does not match Estonian standards");
    return fee;
}
 
Example 11
Project: Rubus   File: XMLConsumer.java   View Source Code Vote up 5 votes
public XMLConsumer(File fileName) throws IOException
{
    writer = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
    addAutoclose(this);
    writer.write("<benchmark-results tstamp=\"" + tstamp() + "\">\n\n");

    nf = NumberFormat.getInstance(Locale.ENGLISH);
    nf.setMaximumFractionDigits(3);
    nf.setGroupingUsed(false);            
}
 
Example 12
Project: aos-Video   File: TvshowDetailedPresenter.java   View Source Code Vote up 5 votes
public TvshowDetailedPresenter(Context context, ExtendedClickListener listener) {
    super(context, AdapterDefaultValuesDetails.INSTANCE, listener);
    mNumberFormat = NumberFormat.getInstance();
    mNumberFormat.setMinimumFractionDigits(1);
    mNumberFormat.setMaximumFractionDigits(1);
    mDateFormat = DateFormat.getDateInstance(DateFormat.LONG);
}
 
Example 13
Project: aos-Video   File: TvshowListPresenter.java   View Source Code Vote up 5 votes
public TvshowListPresenter(Context context, AdapterDefaultValues defaultValues,ExtendedClickListener listener) {
    super(context, defaultValues, listener);
    mNumberFormat = NumberFormat.getInstance();
    mNumberFormat.setMinimumFractionDigits(1);
    mNumberFormat.setMaximumFractionDigits(1);
    mDateFormat = DateFormat.getDateInstance(DateFormat.LONG);
}
 
Example 14
Project: gate-core   File: OntologyMeasures.java   View Source Code Vote up 4 votes
public List<String> getMeasuresRow(Object[] measures, String title) {
  List<AnnotationDiffer> differs = new ArrayList<AnnotationDiffer>(
    getDifferByTypeMap().values());
  AnnotationDiffer differ = new AnnotationDiffer(differs);
  NumberFormat f = NumberFormat.getInstance(Locale.ENGLISH);
  f.setMaximumFractionDigits(2);
  f.setMinimumFractionDigits(2);
  List<String> row = new ArrayList<String>();
  row.add(title);
  row.add(Integer.toString(differ.getCorrectMatches()));
  row.add(Integer.toString(differ.getMissing()));
  row.add(Integer.toString(differ.getSpurious()));
  row.add(Integer.toString(differ.getPartiallyCorrectMatches()));
  for (Object object : measures) {
    String measure = (String) object;
    double beta = Double.valueOf(
      measure.substring(1,measure.indexOf('-')));
    if (measure.endsWith("strict")) {
      row.add(f.format(differ.getPrecisionStrict()));
      row.add(f.format(differ.getRecallStrict()));
      row.add(f.format(differ.getFMeasureStrict(beta)));
    } else if (measure.endsWith("strict BDM")) {
      row.add(f.format(getPrecisionStrictBdm()));
      row.add(f.format(getRecallStrictBdm()));
      row.add(f.format(getFMeasureStrictBdm(beta)));
    } else if (measure.endsWith("lenient")) {
      row.add(f.format(differ.getPrecisionLenient()));
      row.add(f.format(differ.getRecallLenient()));
      row.add(f.format(differ.getFMeasureLenient(beta)));
    } else if (measure.endsWith("lenient BDM")) {
      row.add(f.format(getPrecisionLenientBdm()));
      row.add(f.format(getRecallLenientBdm()));
      row.add(f.format(getFMeasureLenientBdm(beta)));
    } else if (measure.endsWith("average")) {
      row.add(f.format(differ.getPrecisionAverage()));
      row.add(f.format(differ.getRecallAverage()));
      row.add(f.format(differ.getFMeasureAverage(beta)));
    } else if (measure.endsWith("average BDM")) {
      row.add(f.format(getPrecisionAverageBdm()));
      row.add(f.format(getRecallAverageBdm()));
      row.add(f.format(getFMeasureAverageBdm(beta)));
    }
  }
  return row;
}
 
Example 15
Project: SmartChart   File: ValueFormatterHelper.java   View Source Code Vote up 4 votes
public void determineDecimalSeparator() {
    NumberFormat numberFormat = NumberFormat.getInstance();
    if (numberFormat instanceof DecimalFormat) {
        decimalSeparator = ((DecimalFormat) numberFormat).getDecimalFormatSymbols().getDecimalSeparator();
    }
}
 
Example 16
Project: jspoon   File: HtmlField.java   View Source Code Vote up 4 votes
private Number getNumberFromString(String value) throws ParseException {
    NumberFormat numberFormat = NumberFormat.getInstance(locale);
    return numberFormat.parse(value);
}
 
Example 17
Project: alfresco-data-model   File: Duration.java   View Source Code Vote up 4 votes
/**
 * Format in human readable form
 * 
 * TODO: I18n
 */

public String formattedString()
{
   StringBuffer buffer = new StringBuffer(128);
   if (!m_positive)
   {
      buffer.append("-");
   }
   if (m_years != 0)
   {
      if (buffer.length() > 0)
         buffer.append(" ");
      buffer.append(m_years);
      buffer.append((m_years == 1) ? " Year" : " Years");

   }
   if (m_months != 0)
   {
      if (buffer.length() > 0)
         buffer.append(" ");
      buffer.append(m_months);
      buffer.append((m_months == 1) ? " Month" : " Months");
   }
   if (m_days != 0)
   {
      if (buffer.length() > 0)
         buffer.append(" ");
      buffer.append(m_days);
      buffer.append((m_days == 1) ? " Day" : " Days");
   }
   if (hasTime())
   {
      if (m_hours != 0)
      {
         if (buffer.length() > 0)
            buffer.append(" ");
         buffer.append(m_hours);
         buffer.append((m_hours == 1) ? " Hour" : " Hours");
      }
      if (m_mins != 0)
      {
         if (buffer.length() > 0)
            buffer.append(" ");
         buffer.append(m_mins);
         buffer.append((m_mins == 1) ? " Minute" : " Minutes");
      }
      if ((m_seconds != 0) || (m_nanos != 0))
      {
         if (buffer.length() > 0)
            buffer.append(" ");
         BigDecimal a = new BigDecimal(m_seconds);
         BigDecimal b = new BigDecimal(m_nanos);
         a = a.add(b.divide(new BigDecimal(1000000000), 9, BigDecimal.ROUND_HALF_EVEN));
         NumberFormat nf = NumberFormat.getInstance();
         String formatted = nf.format(a);
         buffer.append(formatted);
         buffer.append(formatted.equals("1") ? " Second" : " Seconds");
      }

   }

   return buffer.toString();
}
 
Example 18
Project: openjdk-jdk10   File: RoundingAndPropertyTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) {

        if ((args.length >= 1) &&
            (args[0].equals("-gengold")))
            generatesGoldenFormattedValuesClass();
        else {
            System.out.println("\nChecking correctness of formatting with digit localization.");
            System.out.println("=============================================================");
            int localizationErrors = testLocalizationValues();
            if (localizationErrors != 0)
                System.out.println("*** Failure in localization tests : " +
                                   localizationErrors + " errors detected ");
            else System.out.println(" Tests for full localization of digits all passed.");

            DecimalFormat df = (DecimalFormat)
                NumberFormat.getInstance(GoldenDoubleValues.TestLocale);
            DecimalFormat cf = (DecimalFormat)
                NumberFormat.getCurrencyInstance(GoldenDoubleValues.TestLocale);

            System.out.println("\nChecking correctness of formating for golden values.");
            System.out.println("=============================================================");
            int goldenValuesErrors = testGoldenValues(df,cf);
            if (goldenValuesErrors != 0)
                System.out.println("*** Failure in goldenValues tests : " +
                                   goldenValuesErrors + " errors detected ");
            else System.out.println(" Tests for golden values all passed.");

            System.out.println("\nChecking behavior of property changes for decimal case.");
            System.out.println("=============================================================");
            int decimalTestsErrors = testSettersAndFastPath(df, false);
            if (decimalTestsErrors != 0)
                System.out.println("*** Failure in decimal property changes tests : " +
                                   decimalTestsErrors + " errors detected ");
            else System.out.println(" Tests for decimal property changes all passed.");

            System.out.println("\nChecking behavior of property changes for currency case.");
            System.out.println("=============================================================");
            int currencyTestsErrors = testSettersAndFastPath(cf, true);
            if (currencyTestsErrors != 0)
                System.out.println("*** Failure in currency property changes tests : " +
                                   currencyTestsErrors + " errors detected ");
            else System.out.println(" Tests for currency property chamges all passed.");

            if ((localizationErrors > 0) ||
                (goldenValuesErrors > 0) ||
                (decimalTestsErrors > 0) ||
                (currencyTestsErrors > 0))
                throw new RuntimeException(
                    "Failed with " +
                    (localizationErrors + goldenValuesErrors +
                     decimalTestsErrors + currencyTestsErrors) +
                    " error(s).");
        }
    }
 
Example 19
Project: parabuild-ci   File: StandardCategoryLabelGenerator.java   View Source Code Vote up 4 votes
/**
 * Creates a new generator with a default number formatter.
 */
public StandardCategoryLabelGenerator() {
    super(DEFAULT_LABEL_FORMAT_STRING, NumberFormat.getInstance());
}
 
Example 20
Project: openjdk-jdk10   File: JTable.java   View Source Code Vote up 4 votes
public void setValue(Object value) {
    if (formatter == null) {
        formatter = NumberFormat.getInstance();
    }
    setText((value == null) ? "" : formatter.format(value));
}