Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getInstance.

Prototype

public static final NumberFormat getInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:gov.nasa.arc.geocam.geocam.GeoCamMobile.java

private void updateLocation(Location location) {
    double lat, lon;
    int status;/*from w  ww  . j ava  2s  .c  o  m*/

    if (location == null) {
        lat = 0.0;
        lon = 0.0;
        status = LocationProvider.TEMPORARILY_UNAVAILABLE;
    } else {
        mLocation = location;
        mLocationProvider = mLocation.getProvider();
        status = LocationProvider.AVAILABLE;
        lat = mLocation.getLatitude();
        lon = mLocation.getLongitude();
    }

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(6);
    TextView latText = (TextView) findViewById(R.id.main_latitude_textview);
    TextView lonText = (TextView) findViewById(R.id.main_longitude_textview);
    latText.setText(nf.format(lat) + DEGREE_SYMBOL);
    lonText.setText(nf.format(lon) + DEGREE_SYMBOL);

    ((TextView) findViewById(R.id.main_location_provider_textview)).setText(mLocationProvider);
    TextView locationStatusText = ((TextView) findViewById(R.id.main_location_status_textview));
    switch (status) {
    case LocationProvider.AVAILABLE:
        locationStatusText.setText("available");
        break;
    case LocationProvider.TEMPORARILY_UNAVAILABLE:
        locationStatusText.setText("unavailable");
        break;
    case LocationProvider.OUT_OF_SERVICE:
        locationStatusText.setText("no service");
        break;
    default:
        locationStatusText.setText("unknown");
        break;
    }
}

From source file:com.rockhoppertech.music.Note.java

public String getString() {
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);/*from ww  w. j av a  2s.c  om*/
    nf.setMinimumFractionDigits(2);
    nf.setMaximumIntegerDigits(3);
    // nf.setMinimumIntegerDigits(3);
    PitchFormat pf = PitchFormat.getInstance();
    return String.format("%s,%s,%s", pf.format(pitch).trim(), nf.format(startBeat),
            DurationParser.getDurationString(duration));
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private String parseAttributes(String data) throws RuntimeException {
    String selection = Constants.FIELD_ID + " = ?";
    Cursor attributes = mLayer.query(null, selection, new String[] { mItemId + "" }, null, null);
    if (null == attributes || attributes.getCount() == 0)
        return data;

    if (attributes.moveToFirst()) {
        for (int i = 0; i < attributes.getColumnCount(); i++) {
            String column = attributes.getColumnName(i);
            String text, alias;//from   w ww .  ja  va2  s . c o m

            if (column.startsWith(Constants.FIELD_GEOM_))
                continue;

            if (column.equals(Constants.FIELD_GEOM)) {
                switch (mLayer.getGeometryType()) {
                case GTPoint:
                    try {
                        GeoPoint pt = (GeoPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.coordinates), formatCoordinates(pt));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPoint:
                    try {
                        GeoMultiPoint mpt = (GeoMultiPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.center),
                                formatCoordinates(mpt.getEnvelope().getCenter()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTLineString:
                    try {
                        GeoLineString line = (GeoLineString) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), line.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiLineString:
                    try {
                        GeoMultiLineString multiline = (GeoMultiLineString) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), multiline.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTPolygon:
                    try {
                        GeoPolygon polygon = (GeoPolygon) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPolygon:
                    try {
                        GeoMultiPolygon polygon = (GeoMultiPolygon) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                default:
                    continue;
                }
            }

            Field field = mLayer.getFieldByName(column);
            int fieldType = field != null ? field.getType() : Constants.NOT_FOUND;
            switch (fieldType) {
            case GeoConstants.FTInteger:
                text = attributes.getInt(i) + "";
                break;
            case GeoConstants.FTReal:
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(4);
                nf.setGroupingUsed(false);
                text = nf.format(attributes.getDouble(i));
                break;
            case GeoConstants.FTDate:
            case GeoConstants.FTTime:
            case GeoConstants.FTDateTime:
                text = formatDateTime(attributes.getLong(i), fieldType);
                break;
            default:
                text = toString(attributes.getString(i));
                Pattern pattern = Pattern.compile(URL_PATTERN);
                Matcher match = pattern.matcher(text);
                while (match.matches()) {
                    String url = text.substring(match.start(), match.end());
                    text = text.replaceFirst(URL_PATTERN, "<a href = '" + url + "'>" + url + "</a>");
                    match = pattern.matcher(text.substring(match.start() + url.length() * 2 + 17));
                }
                break;
            }

            if (field != null)
                alias = field.getAlias();
            else if (column.equals(Constants.FIELD_ID))
                alias = Constants.FIELD_ID;
            else
                alias = "";

            data += getRow(alias, text);
        }
    }

    attributes.close();
    return data;
}

From source file:com.kyne.webby.rtk.web.WebServer.java

@SuppressWarnings("unchecked")
public JSONObject getBackupJSON() {

    final JSONArray dateListJSON = new JSONArray();
    final File backupDir = new File("Backups");
    if (!backupDir.exists()) {
        backupDir.mkdir();//from  w  ww  .  ja  v a2s  .co  m
    }
    final File[] backupFiles = backupDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, final String name) {
            return new File(dir, name).isFile() && name.endsWith("zip");
        }
    });
    final SimpleDateFormat zipFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
    final SimpleDateFormat friendlyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");

    final Map<Date, List<File>> backupByDays = new HashMap<Date, List<File>>();
    for (final File backupFile : backupFiles) {
        Date backupDate = null;
        Date backupDay = null;
        try {
            backupDate = zipFormat.parse(backupFile.getName());
            final String day = dayFormat.format(backupDate);
            backupDay = dayFormat.parse(day);
        } catch (final ParseException e) {
            LogHelper.warn("The backup file " + backupFile.getName()
                    + " is not well formed. Format should be yyyyMMdd_HHmmss.zip");
        }
        if (!backupByDays.containsKey(backupDay)) {
            backupByDays.put(backupDay, new ArrayList<File>());
        }
        backupByDays.get(backupDay).add(backupFile);
    }
    final ArrayList<Date> sortedDays = new ArrayList<Date>(backupByDays.keySet());
    Collections.sort(sortedDays, new Comparator<Date>() {
        @Override
        public int compare(final Date o1, final Date o2) {
            return o2.compareTo(o1);
        }
    });

    final double MB = 1024 * 1024;

    for (final Date day : sortedDays) {
        final String dayStr = dayFormat.format(day);
        final JSONObject dateJSON = new JSONObject();
        final JSONArray backups = new JSONArray();
        for (final File backupFile : backupByDays.get(day)) {
            final JSONObject backup = new JSONObject();
            Date backupDate = null;
            try {
                backupDate = zipFormat.parse(backupFile.getName());
            } catch (final ParseException e) {
                /**/ }
            backup.put("date", backupDate == null ? "???" : friendlyFormat.format(backupDate));
            final long byteSize = backupFile.length();
            backup.put("size", NumberFormat.getInstance().format(byteSize / MB) + " MB");
            backup.put("name", backupFile.getName());
            backups.add(backup);
        }
        dateJSON.put("day", dayStr);
        dateJSON.put("backups", backups);

        dateListJSON.add(dateJSON);
    }
    final JSONObject backupJSON = new JSONObject();
    backupJSON.put("dates", dateListJSON);

    return backupJSON;
}

From source file:com.alibaba.druid.benckmark.pool.PoolPerformanceTest.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {
    //ThreadUtils.doSleep(600000);
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();// w w  w .ja v a 2s  .  c  o m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);
    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;
    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + "; YGC " + ygc + " FGC " + fullGC + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

From source file:io.plaidapp.ui.PlayerActivity.java

private void setFollowerCount(int count) {
    followerCount = count;/*from w  w  w .  j  a v a 2  s  .  c  o m*/
    followersCount.setText(getResources().getQuantityString(R.plurals.follower_count, followerCount,
            NumberFormat.getInstance().format(followerCount)));
    if (followerCount == 0) {
        followersCount.setBackground(null);
    }
}

From source file:Human1.java

public void init() {

    // set up a NumFormat object to print out float with only 3 fraction
    // digits//from   w  w  w.  j a v  a  2 s. c om
    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    canvas = new Canvas3D(config);

    add("Center", canvas);

    u = new SimpleUniverse(canvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= offScreenScale;
        dim.height *= offScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);
    }

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();
    u.addBranchGraph(scene);

    view = u.getViewer().getView();

    add("East", guiPanel());
}

From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java

/**
 * Return a NumberFormat to use for Conversion.
 *
 * @return The NumberFormat.//from   w w  w . ja  va2  s.  co m
 */
private NumberFormat getFormat() {
    NumberFormat format = null;
    if (pattern != null) {
        if (locale == null) {
            format = new DecimalFormat(pattern);
        } else {
            DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
            format = new DecimalFormat(pattern, symbols);
        }
    } else {
        if (locale == null) {
            format = NumberFormat.getInstance();
        } else {
            format = NumberFormat.getInstance(locale);
        }
    }
    if (!allowDecimals) {
        format.setParseIntegerOnly(true);
    }
    return format;
}

From source file:com.opera.core.systems.scope.services.ums.EcmaScriptDebugger.java

protected Object parseNumber(String value) {
    Number number;/*  ww w  .  ja v a  2s. co  m*/
    try {
        number = NumberFormat.getInstance().parse(value);
        if (number instanceof Long)
            return number.longValue();
        else
            return number.doubleValue();
    } catch (ParseException e) {
        throw new WebDriverException("The result from the script can not be parsed");
    }
}