Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

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

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * localize a string value depending on datatype and locale
 *
 * @param owner the BindingElement which is localized
 * @param type  the datatype of the bound Node
 * @param value the string value to convert
 * @return returns a localized representation of the input string
 *///  www. j a  va2s .  c o m
public static String localiseValue(BindingElement owner, Element state, String type, String value)
        throws XFormsException {
    if (value == null || value.equals("")) {
        return value;
    }
    String tmpType = type;
    if (tmpType != null && tmpType.contains(":")) {
        tmpType = tmpType.substring(tmpType.indexOf(":") + 1, tmpType.length());
    }
    if (Config.getInstance().getProperty(XFormsProcessorImpl.BETTERFORM_ENABLE_L10N, "true").equals("true")) {

        Locale locale = (Locale) owner.getModel().getContainer().getProcessor().getContext()
                .get(XFormsProcessorImpl.BETTERFORM_LOCALE);
        if (tmpType == null) {
            tmpType = owner.getModelItem().getDeclarationView().getDatatype();
        }
        if (tmpType == null) {
            LOGGER.debug(DOMUtil.getCanonicalPath(owner.getInstanceNode()) + " has no type, assuming 'string'");
            return value;
        }
        if (tmpType.equalsIgnoreCase("float") || tmpType.equalsIgnoreCase("decimal")
                || tmpType.equalsIgnoreCase("double")) {
            if (value.equals(""))
                return value;
            if (value.equals("NaN"))
                return value; //do not localize 'NaN' as it returns strange characters
            try {
                NumberFormat formatter = NumberFormat.getNumberInstance(locale);
                if (formatter instanceof DecimalFormat) {
                    //get original number format
                    int separatorPos = value.indexOf(".");
                    if (separatorPos == -1) {
                        formatter.setMaximumFractionDigits(0);
                    } else {
                        int fractionDigitCount = value.length() - separatorPos - 1;
                        formatter.setMinimumFractionDigits(fractionDigitCount);
                    }

                    Double num = Double.parseDouble(value);
                    return formatter.format(num.doubleValue());
                }
            } catch (NumberFormatException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("date")) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d = sf.parse(value);
                return DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(d);
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else if (tmpType.equalsIgnoreCase("dateTime")) {

            //hackery due to lacking pattern for ISO 8601 Timezone representation in SimpleDateFormat
            String timezone = "";
            String dateTime = null;
            if (value.contains("GMT")) {
                timezone = " GMT" + value.substring(value.lastIndexOf(":") - 3, value.length());
                int devider = value.lastIndexOf(":");
                dateTime = value.substring(0, devider) + value.substring(devider + 1, value.length());
            } else if (value.contains("Z")) {
                timezone = "";
                dateTime = value.substring(0, value.indexOf("Z"));

            } else if (value.contains("+")) {
                timezone = value.substring(value.indexOf("+"), value.length());
                dateTime = value.substring(0, value.indexOf("+"));

            } else {
                dateTime = value;
            }
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

            try {
                Date d = sf.parse(dateTime);
                return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale).format(d)
                        + timezone;
            } catch (ParseException e) {
                LOGGER.warn("Value '" + value + "' is no valid " + tmpType);
                return value;
            }

        } else {
            //not logging for type 'string'
            if (LOGGER.isTraceEnabled() && !(tmpType.equals("string"))) {
                LOGGER.trace("Type " + tmpType + " cannot be localized");
            }
        }
    }
    return value;
}

From source file:org.archive.util.ArchiveUtils.java

public static String doubleToString(double val, int maxFractionDigits, int minFractionDigits) {
    // NumberFormat returns U+FFFD REPLACEMENT CHARACTER for NaN which looks
    // like a bug in the UI
    if (Double.isNaN(val)) {
        return "NaN";
    }// w  ww .j a v a 2  s . com
    NumberFormat f = NumberFormat.getNumberInstance(Locale.US);
    f.setMaximumFractionDigits(maxFractionDigits);
    f.setMinimumFractionDigits(minFractionDigits);
    return f.format(val);
}

From source file:com.eu.evaluation.server.eva.EvaluateExcutorTest.java

@Test
public void test() {
    double d = 0.987;
    logger.info("String.format = " + String.format("%.2f", d));
    DecimalFormat df = new DecimalFormat("*.00");
    logger.info("DecimalFormat = " + df.format(d));

    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    logger.info("NumberFormat = " + nf.format(d));

    DecimalFormat formater = new DecimalFormat();
    formater.setMaximumFractionDigits(2);
    formater.setGroupingSize(0);/*from   www  .jav  a 2  s  .c om*/
    formater.setRoundingMode(RoundingMode.FLOOR);
    logger.info("DecimalFormat = " + (formater.format(d)));
}

From source file:org.squale.squalecommon.enterpriselayer.facade.quality.MeasureFacade.java

/**
 * Creation d'une mesure de type Kiviat pour un projet
 * //ww w  .j av  a  2s.  co  m
 * @param pProjectId Id du projet
 * @param pAuditId Id de l'audit
 * @param pAllFactors tous les facteurs (= "true") ou seulement ceux ayant une note ?
 * @throws JrafEnterpriseException en cas de pb Hibernate
 * @return tableau d'objets : la map des donnes + le boolen pour affichage de la case  cocher tous les facteurs
 */
public static Object[] getProjectKiviat(Long pProjectId, Long pAuditId, String pAllFactors)
        throws JrafEnterpriseException {
    Map result = new HashMap();
    JFreeChart projectKiviat = null;
    MeasureDAOImpl measureDAO = MeasureDAOImpl.getInstance();
    // Session Hibernate
    ISession session = null;
    // Boolen conditonnanant l'affichage de la case  cocher "tous les facteurs" dans la page Jsp
    boolean displayCheckBoxFactors = true;
    try {
        // rcupration d'une session
        session = PERSISTENTPROVIDER.getSession();
        // On ajoute les notes de chaque projets sur le kiviat
        ProjectBO project = (ProjectBO) ProjectDAOImpl.getInstance().load(session, pProjectId);
        SortedMap values = new TreeMap();
        // recupere les facteurs du projet
        Collection factorResults = QualityResultDAOImpl.getInstance().findWhere(session, pProjectId, pAuditId);
        // et cree le map nom => note correspondant
        Iterator it = factorResults.iterator();
        ArrayList nullValuesList = new ArrayList();
        while (it.hasNext()) {
            FactorResultBO factor = (FactorResultBO) it.next();
            // le -1 est trait directement par le kiviatMaker
            Float value = new Float(factor.getMeanMark());
            // ajoute la note dans le titre
            // TODO prendre le vritable nom du facteur
            String name = factor.getRule().getName();
            if (value.floatValue() >= 0) {
                // avec 1 seul chiffre aprs la virgule
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMinimumFractionDigits(1);
                nf.setMaximumFractionDigits(1);
                name = name + " (" + nf.format(value) + ")";
            } else {
                // Mmorisation temporaire des facteurs pour lesquels les notes sont nulles : sera utile si l'option
                // "Tous les facteurs" est coche pour afficher uniquement les facteurs ayant une note.
                nullValuesList.add(name);
            }
            values.put(name, value);
        }
        final int FACTORS_MIN = 3;
        if (nullValuesList.size() <= 0 || values.size() <= FACTORS_MIN) {
            displayCheckBoxFactors = false;
        }
        // Seulement les facteurs ayant une note ? ==> suppression des facteurs ayant une note nulle.
        // Mais trois facteurs doivent au moins s'afficher (nuls ou pas !)
        values = deleteFactors(values, nullValuesList, pAllFactors, FACTORS_MIN);

        // recupre le nom de l'audit
        String name = null;
        AuditBO audit = (AuditBO) AuditDAOImpl.getInstance().load(session, pAuditId);
        if (audit.getType().compareTo(AuditBO.MILESTONE) == 0) {
            name = audit.getName();
        }
        if (null == name) {
            DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
            name = df.format(audit.getDate());
        }
        result.put(name, values);

    } catch (Exception e) {
        FacadeHelper.convertException(e, MeasureFacade.class.getName() + ".getMeasures");
    } finally {
        FacadeHelper.closeSession(session, MeasureFacade.class.getName() + ".getMeasures");
    }
    Object[] kiviatObject = { result, new Boolean(displayCheckBoxFactors) };
    return kiviatObject;
}

From source file:org.polymap.kaps.importer.test.NumberFormatterTest.java

public void testThousands() {
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.getDefault());
    nf.setMaximumIntegerDigits(10);/* w  ww.  ja  va2  s. c o m*/
    nf.setMaximumFractionDigits(10);
    nf.setMinimumIntegerDigits(10);
    nf.setMinimumFractionDigits(10);

    System.out.println(nf.format(12345));
}

From source file:com.discursive.jccook.collections.bag.BagExample.java

private void printAlbums(Bag albumBag) {
    Set albums = albumBag.uniqueSet();
    Iterator albumIterator = albums.iterator();
    while (albumIterator.hasNext()) {
        Album album = (Album) albumIterator.next();
        NumberFormat format = NumberFormat.getInstance();
        format.setMinimumIntegerDigits(3);
        format.setMaximumFractionDigits(0);
        System.out.println("\t" + format.format(albumBag.getCount(album)) + " - " + album.getBand());
    }/*from   ww w  .j av a 2s. c o  m*/
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.LocationObj.java

@Override
public void render(Context context, ViewGroup frame, Obj obj, boolean allowInteractions) {
    JSONObject content = obj.getJson();//  www.j av a  2s  .c  om
    TextView valueTV = new TextView(context);
    NumberFormat df = DecimalFormat.getNumberInstance();
    df.setMaximumFractionDigits(5);
    df.setMinimumFractionDigits(5);

    String msg = "I'm at " + df.format(content.optDouble(COORD_LAT)) + ", "
            + df.format(content.optDouble(COORD_LONG));

    valueTV.setText(msg);
    valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    valueTV.setGravity(Gravity.TOP | Gravity.LEFT);
    frame.addView(valueTV);
}

From source file:uk.org.funcube.fcdw.service.PredictorService.java

public SatellitePosition get(Long catnum, Date instant, GroundStationPosition groundStationPosition) {

    SatellitePosition position = null;//from   w  w w  .j  a va  2 s  .c  o m

    List<TleEntity> tleEntities = tleDao.findByCatnum(catnum);

    if (!tleEntities.isEmpty()) {
        final TleEntity tleEntity = tleEntities.get(0);
        final TLE tle = new TLE(tleEntity.getCatnum(), tleEntity.getName(), tleEntity.getSetnum(),
                tleEntity.getYear(), tleEntity.getRefepoch(), tleEntity.getIncl(), tleEntity.getRaan(),
                tleEntity.getEccn(), tleEntity.getArgper(), tleEntity.getMeanan(), tleEntity.getMeanmo(),
                tleEntity.getDrag(), tleEntity.getNddot6(), tleEntity.getBstar(), tleEntity.getOrbitnum(),
                tleEntity.getEpoch(), tleEntity.getXndt2o(), tleEntity.getXincl(), tleEntity.getXnodeo(),
                tleEntity.getEo(), tleEntity.getOmega(), tleEntity.getMo(), tleEntity.getXno(),
                tleEntity.isDeepspace(), tleEntity.getCreateddate());

        Satellite satellite = SatelliteFactory.createSatellite(tle);

        satellite.calculateSatelliteVectors(instant);
        satellite.calculateSatelliteGroundTrack();

        SatPos satPos = satellite.calculateSatPosForGroundStation(groundStationPosition);

        final NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);

        position = new SatellitePosition(numberFormat.format(satPos.getLatitude() / (Math.PI * 2.0) * 360),
                numberFormat.format(satPos.getLongitude() / (Math.PI * 2.0) * 360),
                satPos.isEclipsed() ? "yes" : "no", numberFormat.format(satPos.getEclipseDepth()),
                satPos.isAboveHorizon());
    }

    return position;
}

From source file:ser423.CalculatorSkeleton.java

public String callMethod(String request) {
    JSONObject result = new JSONObject();
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    try {/*from w w w.  ja  v a 2  s. c om*/
        JSONObject theCall = new JSONObject(request);
        String method = theCall.getString("method");
        int id = theCall.getInt("id");
        JSONArray params = null;
        if (!theCall.isNull("params")) {
            params = theCall.getJSONArray("params");
        }
        result.put("id", id);
        result.put("jsonrpc", "2.0");
        double left = 0;
        double right = 0;
        if (params.length() > 0) {
            left = params.getDouble(0);
        }
        if (params.length() > 1) {
            right = params.getDouble(1);
        }
        if (method.equals("add")) {
            System.out.println("request: " + nf.format(left) + " + " + nf.format(right));
            double res = ci.add(left, right);
            result.put("result", res);
        } else if (method.equals("subtract")) {
            System.out.println("request: " + nf.format(left) + " - " + nf.format(right));
            double res = ci.subtract(left, right);
            result.put("result", res);
        } else if (method.equals("multiply")) {
            System.out.println("request: " + nf.format(left) + " * " + nf.format(right));
            double res = ci.multiply(left, right);
            result.put("result", res);
        } else if (method.equals("divide")) {
            System.out.println("request: " + nf.format(left) + " / " + nf.format(right));
            double res = ci.divide(left, right);
            result.put("result", res);
        } else if (method.equals("whoAreYou")) {
            System.out.println("request: whoAreYou");
            result.put("result", ci.whoAreYou());
        }
    } catch (Exception ex) {
        System.out.println("exception in callMethod: " + ex.getMessage());
    }
    return "HTTP/1.0 200 Data follows\nServer:localhost:8080\nContent-Type:text/plain\nContent-Length:"
            + (result.toString()).length() + "\n\n" + result.toString();
}

From source file:org.apache.hadoop.hive.ql.udf.UDFNumberFormat.java

public String evaluate(DoubleWritable d) {
    if (d == null) {
        return null;
    }/*from w  ww.j  av  a 2  s . c  om*/
    double ori = d.get();
    try {
        NumberFormat nFormat = NumberFormat.getNumberInstance();
        nFormat.setMaximumFractionDigits(maxdefault);
        nFormat.setMaximumIntegerDigits(maxdefault);
        nFormat.setGroupingUsed(false);
        return nFormat.format(ori);
    } catch (Exception e) {
        LOG.error("can not format value:  " + ori);
        return null;
    }
}