Example usage for java.text NumberFormat setMinimumFractionDigits

List of usage examples for java.text NumberFormat setMinimumFractionDigits

Introduction

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

Prototype

public void setMinimumFractionDigits(int newValue) 

Source Link

Document

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

Usage

From source file:org.rhq.core.util.StringUtil.java

public static String formatDuration(long duration, int scale, boolean minDigits) {
    long hours;/*from   w  w w.  ja va2 s .  c o  m*/
    long mins;
    int digits;
    double millis;

    hours = duration / 3600000;
    duration -= hours * 3600000;

    mins = duration / 60000;
    duration -= mins * 60000;

    millis = (double) duration / 1000;

    StringBuilder buf = new StringBuilder();

    if ((hours > 0) || (minDigits == false)) {
        buf.append(((hours < 10) && (minDigits == false)) ? ("0" + hours) : String.valueOf(hours)).append(':');
        minDigits = false;
    }

    if ((mins > 0) || (minDigits == false)) {
        buf.append(((mins < 10) && (minDigits == false)) ? ("0" + mins) : String.valueOf(mins)).append(':');
        minDigits = false;
    }

    // Format seconds and milliseconds
    NumberFormat fmt = NumberFormat.getInstance();
    digits = (((minDigits == false) || ((scale == 0) && (millis >= 9.5))) ? 2 : 1);
    fmt.setMinimumIntegerDigits(digits);
    fmt.setMaximumIntegerDigits(2); // Max of 2
    fmt.setMinimumFractionDigits(0); // Don't need any
    fmt.setMaximumFractionDigits(scale);

    buf.append(fmt.format(millis));

    return buf.toString();
}

From source file:com.icloud.framework.http.heritrix.ArchiveUtils.java

private static String doubleToString(double val, int maxFractionDigits, int minFractionDigits) {
    NumberFormat f = NumberFormat.getNumberInstance(Locale.US);
    f.setMaximumFractionDigits(maxFractionDigits);
    f.setMinimumFractionDigits(minFractionDigits);
    return f.format(val);
}

From source file:org.renjin.parser.NumericLiterals.java

public static NumberFormat createRealFormat() {
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMinimumFractionDigits(0);
    format.setMaximumFractionDigits(14);
    format.setGroupingUsed(false);/*from  ww  w  .  j a  v a2s .  c o  m*/
    return format;
}

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

/**
 * Creation d'une mesure de type Kiviat pour un projet
 * //from w  w  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.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  w  w .ja  va  2s .co  m
    NumberFormat f = NumberFormat.getNumberInstance(Locale.US);
    f.setMaximumFractionDigits(maxFractionDigits);
    f.setMinimumFractionDigits(minFractionDigits);
    return f.format(val);
}

From source file:org.oscarehr.common.model.ReportStatistic.java

public String getPercent() {
    NumberFormat percentInstance = NumberFormat.getPercentInstance();
    percentInstance.setMinimumFractionDigits(0);
    percentInstance.setMaximumFractionDigits(2);

    return percentInstance.format(fraction.floatValue());
}

From source file:picocash.model.impl.Money.java

@Override
public String toString() {
    double result = (double) value / 100;
    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    numberFormat.setMinimumFractionDigits(2);
    numberFormat.setMaximumFractionDigits(2);
    return numberFormat.format(result);
}

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
 *//*from  ww  w.  j av  a2  s  .  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.kalypso.ogc.gml.om.table.handlers.ComponentUiDecimalHandler.java

@Override
public Object doGetValue(final IRecord record) {
    final Object value = record.getValue(getComponent());
    if (value == null)
        return ""; //$NON-NLS-1$

    // TODO: maybe we need an 'editFormat' as well?

    if (value instanceof BigDecimal) {
        // force number of digits to be scale; format with correct locale as well
        final NumberFormat format = NumberFormat.getInstance();
        format.setMinimumFractionDigits(((BigDecimal) value).scale());
        return format.format(value);
    }/*from w w w .j  ava2  s.co  m*/

    // IMPORTANT: do not use 'getStringRepresentation'; we need to see internal digits here (else just clicking the cell might change the value)
    return String.format("%f", value); //$NON-NLS-1$
}

From source file:Main.java

private JFormattedTextField setFormat(JFormattedTextField jft, Locale local1, int minFra, int maxFra) {
    NumberFormat numberFormat;
    Locale local = local1;/*from w  w w  .j  av a 2  s . co  m*/
    int setMin = minFra;
    int setMax = maxFra;
    numberFormat = NumberFormat.getCurrencyInstance(local);
    numberFormat.setMinimumFractionDigits(setMin);
    numberFormat.setMaximumFractionDigits(setMax);
    numberFormat.setRoundingMode(RoundingMode.HALF_UP);
    jft = new JFormattedTextField(numberFormat);
    jft.setValue(new Double(342.796));
    return jft;
}