Example usage for java.text NumberFormat format

List of usage examples for java.text NumberFormat format

Introduction

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

Prototype

public final String format(long number) 

Source Link

Document

Specialization of format.

Usage

From source file:org.projectforge.web.statistics.PersonalStatisticsPage.java

public PersonalStatisticsPage(final PageParameters parameters) {
    super(parameters);
    final Label timesheetDisciplineChartTitle = new Label("timesheetDisciplineChartTitle",
            getString("personal.statistics.timesheetDisciplineChart.title"));
    body.add(timesheetDisciplineChartTitle);
    final Shape shape = new Ellipse2D.Float(-3, -3, 6, 6);
    // final Shape shape = null;
    final Stroke stroke = new BasicStroke(3.0f);
    // final Stroke stroke = new BasicStroke(1.0f);
    final EmployeeDO employee = employeeDao.getByUserId(PFUserContext.getUserId());
    double workingHoursPerDay = 8;
    if (employee != null && NumberHelper.greaterZero(employee.getWochenstunden()) == true) {
        workingHoursPerDay = employee.getWochenstunden() / 5;
    }// www.j ava 2 s .  c o  m
    final TimesheetDisciplineChartBuilder chartBuilder = new TimesheetDisciplineChartBuilder();
    final JFreeChart chart1 = chartBuilder.create(timesheetDao, getUser().getId(), workingHoursPerDay,
            LAST_N_DAYS, shape, stroke, true);
    JFreeChartImage image = new JFreeChartImage("timesheetStatisticsImage1", chart1, IMAGE_WIDTH, IMAGE_HEIGHT);
    image.add(AttributeModifier.replace("width", String.valueOf(IMAGE_WIDTH)));
    image.add(AttributeModifier.replace("height", String.valueOf(IMAGE_HEIGHT)));
    body.add(image);
    final NumberFormat format = NumberFormat.getNumberInstance(PFUserContext.getLocale());
    final String planHours = "<span style=\"color: #DE1821; font-weight: bold;\">"
            + format.format(chartBuilder.getPlanWorkingHours()) + "</span>";
    final String actualHours = "<span style=\"color: #40A93B; font-weight: bold;\">"
            + format.format(chartBuilder.getActualWorkingHours()) + "</span>";
    final String numberOfDays = String.valueOf(LAST_N_DAYS);
    final Label timesheetDisciplineChart1Legend = new Label("timesheetDisciplineChart1Legend",
            getLocalizedMessage("personal.statistics.timesheetDisciplineChart1.legend", numberOfDays, planHours,
                    actualHours));
    timesheetDisciplineChart1Legend.setEscapeModelStrings(false);
    body.add(timesheetDisciplineChart1Legend);

    final JFreeChart chart2 = chartBuilder.create(timesheetDao, getUser().getId(), LAST_N_DAYS, shape, stroke,
            true);
    image = new JFreeChartImage("timesheetStatisticsImage2", chart2, IMAGE_WIDTH, IMAGE_HEIGHT);
    image.add(AttributeModifier.replace("width", String.valueOf(IMAGE_WIDTH)));
    image.add(AttributeModifier.replace("height", String.valueOf(IMAGE_HEIGHT)));
    body.add(image);
    final String averageDifference = "<span style=\"color: #DE1821; font-weight: bold;\">"
            + format.format(chartBuilder.getAverageDifferenceBetweenTimesheetAndBooking()) + "</span>";
    final String plannedDifference = "<span style=\"color: #40A93B; font-weight: bold;\">"
            + format.format(chartBuilder.getPlannedAverageDifferenceBetweenTimesheetAndBooking()) + "</span>";
    final Label timesheetDisciplineChart2Legend = new Label("timesheetDisciplineChart2Legend",
            getLocalizedMessage("personal.statistics.timesheetDisciplineChart2.legend", numberOfDays,
                    plannedDifference, averageDifference));
    timesheetDisciplineChart2Legend.setEscapeModelStrings(false);
    body.add(timesheetDisciplineChart2Legend);
}

From source file:uk.ac.gda.dls.client.views.MonitorCompositeFactory.java

void setVal(String newVal) {
    if (decimalPlaces != null) {
        Scanner sc = new Scanner(newVal.trim());
        if (sc.hasNextDouble()) {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(decimalPlaces.intValue());
            newVal = format.format(sc.nextDouble());
        }//  w  w  w .ja va  2  s  .  c o m
        sc.close();
    }
    val = newVal;
    if (!isDisposed())
        display.asyncExec(setTextRunnable);
}

From source file:clus.statistic.RegressionStatBinaryNomiss.java

@Override
public Element getPredictElement(Document doc) {
    Element stats = doc.createElement("RegressionStatBinaryNomiss");
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    Attr examples = doc.createAttribute("examples");
    examples.setValue(fr.format(m_SumWeight));
    stats.setAttributeNode(examples);//from w w  w.  j  av  a  2  s. co  m
    for (int i = 0; i < m_NbAttrs; i++) {
        Element attr = doc.createElement("Target");
        Attr name = doc.createAttribute("name");
        name.setValue(m_Attrs[i].getName());
        attr.setAttributeNode(name);
        attr.setTextContent(fr.format(getMean(i)));
        stats.appendChild(attr);
    }
    return stats;
}

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 .jav a2s. 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:smarthome.FXMLDocumentController.java

@FXML
private void updateColor(ActionEvent event) {
    Color newColor = colorChooser1.getValue();
    currentColor.setFill(newColor);/*from   w  w  w.  ja  v a 2  s  . c o  m*/
    NumberFormat formatter = new DecimalFormat("#0.00");

    String red = formatter.format(newColor.getRed());
    String green = formatter.format(newColor.getGreen());
    String blue = formatter.format(newColor.getBlue());
    System.out.println("R= " + red + "  : G= " + green + "   : B= " + blue);

    new Thread(new Runnable() {
        @Override
        public void run() {

            httpPost("http://" + ipaddress + ":8080/cgi-bin/setRGB.py?R=" + red + "&G=" + green + "&B=" + blue);
            System.out.println("Inside The Thread.");

        }
    }).start();

}

From source file:com.vmware.qe.framework.datadriven.impl.generator.AbstractDataGenerator.java

@Override
public List<HierarchicalConfiguration> generate(HierarchicalConfiguration data,
        HierarchicalConfiguration context) {
    List<HierarchicalConfiguration> combConfig = new ArrayList<>();
    List<HierarchicalConfiguration> dataCombs = data.configurationsAt("data-combination");
    for (HierarchicalConfiguration dataComb : dataCombs) {
        List<HierarchicalConfiguration> sets = dataComb.configurationsAt("set");
        List<List<HierarchicalConfiguration>> combData = new ArrayList<List<HierarchicalConfiguration>>();
        for (HierarchicalConfiguration set : sets) {
            List<HierarchicalConfiguration> elements = set.configurationsAt("element");
            combData.add(elements);/*w ww  .jav a  2s.co  m*/
        }
        List<List<Integer>> setIndexData = new ArrayList<>();
        for (List<HierarchicalConfiguration> set : combData) {
            List<Integer> elements = new ArrayList<>();
            for (int i = 0; i < set.size(); i++) {
                elements.add(i);
            }
            setIndexData.add(elements);
        }
        int id = 1;
        List<List<Integer>> combinations = generateCombinations(setIndexData);
        final NumberFormat format = new DecimalFormat("###000");
        for (List<Integer> comb : combinations) {
            HierarchicalConfiguration combination = new HierarchicalConfiguration();
            combination.addProperty("[@test-id]", format.format(id++));
            for (int i = 0; i < comb.size(); i++) {
                HierarchicalConfiguration element = combData.get(i).get(comb.get(i));
                combination.append(element);
            }
            combConfig.add(combination);
        }
    }
    log.debug("Combinations: " + combConfig.size());
    return combConfig;
}

From source file:com.anrisoftware.globalpom.measurement.ValueToString.java

private void formatValue(StringBuffer buff, Value value, NumberFormat valueFormat, NumberFormat uncFormat) {
    double v = value.getValue();
    double u = value.getUncertainty();
    int sig = value.getSignificant();
    int dec = value.getDecimal();
    buff.append(valueFormat.format(v));
    buff.append(OPEN).append(uncFormat.format(u)).append(CLOSE).append(sig).append(SEP).append(dec).append(SEP);
}

From source file:de.tor.tribes.util.bb.DefStatsFormatter.java

private String[] getStatSpecificReplacements(Stats pStats) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);/*  www  . j  a va  2  s  .c  o m*/
    nf.setMaximumFractionDigits(0);
    String tribe = pStats.getParent().getTribe().toBBCode();
    String killsBefore = nf.format(pStats.getBashDefStart());
    String killsAfter = nf.format(pStats.getBashDefEnd());
    String killsDiff = nf.format(pStats.getBashDefDiff());

    if (pStats.getBashDefDiff() > 0) {
        killsDiff = "[color=green]" + killsDiff + "[/color]";
    } else {
        killsDiff = "[color=red]" + killsDiff + "[/color]";
    }

    long pBefore = pStats.getBashDefStart();
    double perc = 0;
    if (pBefore > 0) {
        perc = (double) 100 * (double) pStats.getBashDefDiff() / (double) pBefore;
    }

    String percentDiff = ((perc >= 0) ? "+" : "") + nf.format(perc) + "%";

    if (perc > 0) {
        percentDiff = "[color=green]" + percentDiff + "[/color]";
    } else {
        percentDiff = "[color=red]" + percentDiff + "[/color]";
    }

    return new String[] { tribe, killsBefore, killsAfter, killsDiff, percentDiff };
}

From source file:de.tor.tribes.util.bb.KillStatsFormatter.java

private String[] getStatSpecificReplacements(Stats pStats) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);//  www.j a  v a2s .  c  o  m
    nf.setMaximumFractionDigits(0);
    String tribe = pStats.getParent().getTribe().toBBCode();
    String killsBefore = nf.format(pStats.getBashOffStart());
    String killsAfter = nf.format(pStats.getBashOffEnd());
    String killsDiff = nf.format(pStats.getBashOffDiff());

    if (pStats.getBashOffDiff() > 0) {
        killsDiff = "[color=green]" + killsDiff + "[/color]";
    } else {
        killsDiff = "[color=red]" + killsDiff + "[/color]";
    }

    long pBefore = pStats.getBashOffStart();
    double perc = 0;
    if (pBefore > 0) {
        perc = (double) 100 * (double) pStats.getBashOffDiff() / (double) pBefore;
    }

    String percentDiff = ((perc >= 0) ? "+" : "") + nf.format(perc) + "%";

    if (perc > 0) {
        percentDiff = "[color=green]" + percentDiff + "[/color]";
    } else {
        percentDiff = "[color=red]" + percentDiff + "[/color]";
    }

    return new String[] { tribe, killsBefore, killsAfter, killsDiff, percentDiff };
}

From source file:com.skilrock.lms.web.scratchService.orderMgmt.common.BOOrderProcessAction.java

public List<Double> getAgtCreditDetails() throws Exception {
    PrintWriter out = getResponse().getWriter();
    GameDetailsHelper gameHelper = new GameDetailsHelper();
    List<Double> accountList = null;
    try {//from  ww w. j av  a  2  s.  co m
        accountList = gameHelper.fetchBOAgentAccDetail(getAgtOrgName());
    } catch (LMSException e) {
        System.out.println("In boOrderProcessAction get Credit details");
        e.printStackTrace();
    }
    HttpSession session = getRequest().getSession();
    double creditrLimit = 0.0;
    double currentCrLimit = 0.0;
    double availableLimit = 0.0;
    if (accountList != null) {
        System.out.println("acountlist not null");
        creditrLimit = accountList.get(0);
        currentCrLimit = accountList.get(1);
        availableLimit = accountList.get(2);
        session.setAttribute("CRLIMIT", currentCrLimit);
        session.setAttribute("CURRBAL", availableLimit);
        // session.setAttribute("CURRBAL",currentBalance);
    }
    // changed by yogesh to display available limit on jsp page(without E
    // type value)
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(2);
    String availableCreditTodisplay = nf.format(availableLimit).replace(",", "");
    System.out.println("available credit as string#######################3  " + availableCreditTodisplay);
    String html = "<tr><td><font color='red'>  Order Cannot be Dispatched !   Available Credit Amount of '"
            + getAgtOrgName()
            + "' is Insufficient </font> </td><td><br><font color='red'>Available Credit Amount is :</font><input type='text' readonly='true' name='crBal' id='crBal' value='"
            + availableCreditTodisplay + "'/></td></tr>";
    System.out.println(html + "99999999999");
    response.setContentType("text/html");

    out.print(html);
    System.out.println("crredit amount" + currentCrLimit + "avalaible credit" + availableLimit);
    return null;

}