Example usage for java.text DecimalFormat setRoundingMode

List of usage examples for java.text DecimalFormat setRoundingMode

Introduction

In this page you can find the example usage for java.text DecimalFormat setRoundingMode.

Prototype

@Override
public void setRoundingMode(RoundingMode roundingMode) 

Source Link

Document

Sets the java.math.RoundingMode used in this DecimalFormat.

Usage

From source file:regresiones.RegresionSimple.java

public void Resolver(JTabbedPane resultados) {

    for (int i = 0; i < 9; i++) {
        sumatorias[i] = 0.0;//from  w w  w  .  j  a  v  a2  s . c o  m
    }
    try {
        System.out.println("TOTAL DE DATOS: " + N);
        for (int i = 0; i < N; i++) {
            xiyi[i] = datos[i][0] * datos[i][1];
            System.out.println("X*Y" + i + ": " + xiyi[i]);
            x2[i] = datos[i][0] * datos[i][0]; //elevamos al cuadrado las x's
            y2[i] = datos[i][1] * datos[i][1]; //elevamos al cuadrado las y's
            sumatorias[0] += datos[i][0]; //sumatoria de x
            sumatorias[1] += datos[i][1]; //sumatoria de y

        }
        //sumatoria de xi*yi
        for (int j = 0; j < N; j++) {
            sumatorias[2] += xiyi[j];
        }

        //sumatoria de x^2
        for (int j = 0; j < N; j++) {
            sumatorias[3] += x2[j];
        }

        //sumatoria de y^2
        for (int j = 0; j < N; j++) {
            sumatorias[4] += y2[j];
        }

        mediax = sumatorias[0] / N;
        mediay = sumatorias[1] / N;

        System.out.println("RAIS 25: " + Math.sqrt(25));

        DecimalFormat df = new DecimalFormat("##.##");
        df.setRoundingMode(RoundingMode.DOWN);
        System.out.println("redondeo x^2-- " + df.format(sumatorias[3]));
        System.out.println("redondeo y^2-- " + df.format(sumatorias[4]));
        redondeoSumatoriax2 = Double.parseDouble(df.format(sumatorias[3]));
        redondeoSumatoriay2 = Double.parseDouble(df.format(sumatorias[4]));
        dxy = ((sumatorias[2]) / N) - mediax * mediay;
        dy = Math.sqrt(((redondeoSumatoriay2 / N) - (mediay * mediay)));
        dx = Math.sqrt(((redondeoSumatoriax2 / N) - (mediax * mediax)));

        b1 = ((sumatorias[2] * N) - sumatorias[0] * sumatorias[1])
                / ((sumatorias[3] * N) - (sumatorias[0] * sumatorias[0]));
        b0 = (sumatorias[1] / N) - ((b1 * sumatorias[0]) / N);

        // Y ESTIMADA
        for (int i = 0; i < N; i++) {
            yEstimada[i] = b0 + (b1 * datos[i][0]);
        }

        Se = Math.sqrt((sumatorias[4] - (b0 * sumatorias[1]) - (b1 * sumatorias[2])) / (N - 2));
        r = dxy / (dx * dy);
        System.out.println("sum x: " + sumatorias[0]);
        System.out.println("sum y: " + sumatorias[1]);
        System.out.println("sum x*y: " + sumatorias[2]);
        System.out.println("sum x^2: " + sumatorias[3]);
        System.out.println("sum y^2: " + sumatorias[4]);
        System.out.println("DX7: " + dxy);
        System.out.println("DY: " + dy);
        System.out.println("DX: " + dx);
        System.out.println("B0: " + b0);
        System.out.println("B1: " + b1);

        // mostramos resultados para la pestaa resultados***********************************************************************
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.white);
        JLabel titulo = new JLabel("Resultados");//creamos el titulo
        panel.add(titulo, BorderLayout.PAGE_START);//lo agregamos al inicio
        jtable = new JTable();//creamos la tabla a mostrar
        jtable.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 0, 0), 2, true));
        jtable.setFont(new java.awt.Font("Arial", 1, 14));
        jtable.setColumnSelectionAllowed(true);
        jtable.setCursor(new java.awt.Cursor(java.awt.Cursor.N_RESIZE_CURSOR));
        jtable.setInheritsPopupMenu(true);
        jtable.setMinimumSize(new java.awt.Dimension(80, 80));
        String[] titulos = { "X", "Y", "Xi*Yi", "X2", "Y2", "Y estimada" };//los titulos de la tabla
        arregloFinal = new String[N][6];
        DecimalFormat formato = new DecimalFormat("0.00");
        for (int i = 0; i < N; i++) {//armamos el arreglo
            arregloFinal[i][0] = datos[i][0] + ""; //X
            arregloFinal[i][1] = datos[i][1] + "";//Y
            arregloFinal[i][2] = formato.format(xiyi[i]);
            arregloFinal[i][3] = formato.format(x2[i]);
            arregloFinal[i][4] = formato.format(y2[i]);
            arregloFinal[i][5] = formato.format(yEstimada[i]);
        }
        DefaultTableModel TableModel = new DefaultTableModel(arregloFinal, titulos);
        jtable.setModel(TableModel);
        JScrollPane jScrollPane1 = new JScrollPane();
        jScrollPane1.setViewportView(jtable);
        jtable.getColumnModel().getSelectionModel()
                .setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);

        panel.add(jScrollPane1, BorderLayout.CENTER);
        JPanel panel2 = new JPanel(new GridLayout(0, 4));//creo un panel con rejilla de 4 columnas
        JLabel etiquetaN = new JLabel("N");
        JTextField cajaN = new JTextField();
        cajaN.setText(N + "");
        JLabel etiquetab0 = new JLabel("b0");
        JTextField cajab0 = new JTextField();
        cajab0.setText(b0 + "");
        JLabel etiquetab1 = new JLabel("b1");
        JTextField cajab1 = new JTextField();
        cajab1.setText(b1 + "");
        JLabel etiquetadxy = new JLabel("DXy");
        JTextField cajadxy = new JTextField();
        cajadxy.setText(dxy + "");
        JLabel etiquetadx = new JLabel("DX");
        JTextField cajadx = new JTextField();
        cajadx.setText(dx + "");
        JLabel etiquetady = new JLabel("DY");
        JTextField cajady = new JTextField();
        cajady.setText(dy + "");
        JLabel etiquetaR = new JLabel("R");
        JTextField cajaR = new JTextField();
        cajaR.setText(r + "");
        JLabel etiquetaSE = new JLabel("SE");
        JTextField cajaSE = new JTextField();
        cajaSE.setText(Se + "");
        JButton boton = new JButton("Exportar a PDF");
        boton.addActionListener(this);
        panel2.add(etiquetaN);
        panel2.add(cajaN);
        panel2.add(etiquetab0);
        panel2.add(cajab0);
        panel2.add(etiquetab1);
        panel2.add(cajab1);
        panel2.add(etiquetadxy);
        panel2.add(cajadxy);
        panel2.add(etiquetadx);
        panel2.add(cajadx);
        panel2.add(etiquetady);
        panel2.add(cajady);
        panel2.add(etiquetaR);
        panel2.add(cajaR);
        panel2.add(etiquetaSE);
        panel2.add(cajaSE);
        panel2.add(boton);
        panel.add(panel2, BorderLayout.SOUTH);//agrego el panel2 con rejilla en el panel principal al sur
        resultados.addTab("resultado", panel);
        //**************************************************************************************
        //intervalos de confianza
        JPanel intervalos = new JPanel(new BorderLayout());
        JPanel variables = new JPanel(new GridLayout(0, 2));
        JLabel variableX1 = new JLabel("X1");
        cajaVariableX1 = new JTextField();
        boton = new JButton("calcular");
        boton.addActionListener(this);
        JLabel variableEfectividad = new JLabel("Efectividad");
        String[] efectividades = { "80", "85", "90", "95", "99" };
        combo = new JComboBox(efectividades);
        variables.add(variableX1);
        variables.add(cajaVariableX1);
        variables.add(variableEfectividad);
        variables.add(combo);
        variables.add(boton);//comentario
        //cometario2
        intervalos.add(variables, BorderLayout.NORTH);
        jtable2 = new JTable();//creamos la tabla a mostrar
        jtable2.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(255, 0, 0), 2, true));
        jtable2.setFont(new java.awt.Font("Arial", 1, 14));
        jtable2.setColumnSelectionAllowed(true);
        jtable2.setCursor(new java.awt.Cursor(java.awt.Cursor.N_RESIZE_CURSOR));
        jtable2.setInheritsPopupMenu(true);
        jtable2.setMinimumSize(new java.awt.Dimension(80, 80));
        String[] titulos2 = { "Y estimada", "Li", "Ls" };//los titulos de la tabla
        String[][] pruebaIntervalos = { { "", "", "" } };
        DefaultTableModel TableModel2 = new DefaultTableModel(pruebaIntervalos, titulos2);
        jtable2.setModel(TableModel2);
        JScrollPane jScrollPane2 = new JScrollPane();
        jScrollPane2.setViewportView(jtable2);
        jtable2.getColumnModel().getSelectionModel()
                .setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        intervalos.add(jScrollPane2, BorderLayout.CENTER);
        resultados.addTab("intervalos", intervalos);
        // ***********************************************************************
        JPanel graficas = new JPanel(new GridLayout(0, 1));
        XYDataset dataset = createSampleDataset();
        JFreeChart chart = ChartFactory.createXYLineChart("Grafica", "X", "Y", dataset,
                PlotOrientation.VERTICAL, true, false, false);
        XYPlot plot = (XYPlot) chart.getPlot();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, true);
        renderer.setSeriesShapesVisible(0, true);
        renderer.setSeriesLinesVisible(1, true);
        renderer.setSeriesShapesVisible(1, true);
        plot.setRenderer(renderer);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 300));
        graficas.add(chartPanel);//agregamos la primer grafica
        resultados.addTab("Graficas", graficas);
        //IMPRIMIR JTABLE
        /* MessageFormat headerFormat = new MessageFormat("MI CABECERA");
         MessageFormat footerFormat = new MessageFormat("- Pgina {0} -");
         jtable.print(PrintMode.FIT_WIDTH, headerFormat, footerFormat);
         */

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.ThreadViewFragment.java

/**
 * When comment is selected, additional information is displayed in the form
 * of location coordinates and action buttons.
 * This method sets that location field TextView in
 * the view.// w  w  w  .j av  a  2  s.c  o m
 * 
 * @param view The View of the Comment that was selected.
 * @param comment The Comment itself that was selected by the user.
 */
public void setLocationField(View view, Comment comment) {
    TextView replyLocationText = (TextView) view.findViewById(R.id.thread_view_comment_location);
    GeoLocation repLocCom = comment.getLocation();

    if (repLocCom != null) {
        if (repLocCom.getLocationDescription() != null) {
            replyLocationText.setText("near: " + repLocCom.getLocationDescription());
        } else {
            DecimalFormat format = new DecimalFormat();
            format.setRoundingMode(RoundingMode.HALF_EVEN);
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(4);

            replyLocationText.setText("Latitude: " + format.format(repLocCom.getLatitude()) + " Longitude: "
                    + format.format(repLocCom.getLongitude()));
        }
    } else {
        replyLocationText.setText("Error: No location found");
    }
}

From source file:ca.ualberta.cmput301w14t08.geochan.adapters.ThreadViewAdapter.java

/**
 * Sets the required fields of the orignal post of the thread.
 * Title, creator, comment, timestamp, location.
 * //from  www . j  a  v a 2 s .  c o m
 * @param convertView
 *            View container of a listView item.
 */
private void setOPFields(View convertView) {
    // Thread title
    TextView title = (TextView) convertView.findViewById(R.id.thread_view_op_threadTitle);
    // Special case of Viewing a Favourite Comment in ThreadView
    if (thread.getTitle().equals("")) {
        title.setVisibility(View.GONE);
        LinearLayout buttons = (LinearLayout) convertView.findViewById(R.id.thread_view_op_buttons);
        buttons.setVisibility(View.GONE);
    } else {
        title.setText(thread.getTitle());
    }
    // Thread creator
    TextView threadBy = (TextView) convertView.findViewById(R.id.thread_view_op_commentBy);
    threadBy.setText(
            "Posted by " + thread.getBodyComment().getUser() + "#" + thread.getBodyComment().getHash() + "  ");
    if (HashHelper.getHash(thread.getBodyComment().getUser()).equals(thread.getBodyComment().getHash())) {
        threadBy.setBackgroundResource(R.drawable.username_background_thread_rect);
        threadBy.setTextColor(Color.WHITE);
    }

    // Thread body comment
    TextView body = (TextView) convertView.findViewById(R.id.thread_view_op_commentBody);
    body.setText(thread.getBodyComment().getTextPost());
    // Thread timestamp
    TextView threadTime = (TextView) convertView.findViewById(R.id.thread_view_op_commentDate);
    threadTime.setText(thread.getBodyComment().getCommentDateString());
    // Location text
    TextView origPostLocationText = (TextView) convertView.findViewById(R.id.thread_view_op_locationText);
    GeoLocation loc = thread.getBodyComment().getLocation();
    String locDescriptor = loc.getLocationDescription();
    if (loc != null) {
        if (locDescriptor != null) {
            origPostLocationText.setText("near: " + locDescriptor);
        } else {
            // The rounding of long and lat for max 4 decimal digits.
            DecimalFormat format = new DecimalFormat();
            format.setRoundingMode(RoundingMode.HALF_EVEN);
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(4);

            origPostLocationText.setText("Latitude: " + format.format(loc.getLatitude()) + " Longitude: "
                    + format.format(loc.getLongitude()));
        }
    }

    // Set the thumbnail if there is an image
    if (thread.getBodyComment().hasImage()) {
        ImageButton thumbnail = (ImageButton) convertView.findViewById(R.id.thread_view_comment_thumbnail);
        thumbnail.setVisibility(View.VISIBLE);
        thumbnail.setFocusable(false);
        thumbnail.setImageBitmap(thread.getBodyComment().getImageThumb());
    }
}

From source file:android.melbournehistorymap.MapsActivity.java

private void updateMap() {

    //Now get the maps central location
    LatLng mapCenter = mMap.getCameraPosition().target;
    //clear markers
    mMap.clear();/*  www.j  a  v  a 2 s  . c o  m*/

    //if user tries to zoom to far out of the world, bring them back down to earth...
    if (mMap.getCameraPosition().zoom < ZOOM_RESTRICT_LEVEL) {
        CameraPosition cameraPosition = new CameraPosition.Builder().target(mapCenter) // Sets the center of the map to location user
                .zoom(ZOOM_RESTRICT_LEVEL) // Sets the zoom
                .bearing(0) // Sets the orientation of the camera to east
                .tilt(25) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    //rebuild lat/lng variable to be used for Google Places API requests
    double lat = mapCenter.latitude;
    double lng = mapCenter.longitude;
    double zoom = mMap.getCameraPosition().zoom;

    LatLng leftBorder = mMap.getProjection().getVisibleRegion().farLeft;

    //Work out distance between current location and place location
    //Source Library: https://github.com/googlemaps/android-maps-utils

    double radius = SphericalUtil.computeDistanceBetween(mapCenter, leftBorder);

    //Now that we have the new long/latitude of the camera position include zoom level
    //Lets check the database to determine if the user has been here already
    //Set DB helper
    DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);
    //Open DB as readable only.
    SQLiteDatabase db = myDBHelper.getWritableDatabase();
    //Prepare DB Search variables
    DecimalFormat dfLat = new DecimalFormat("#.##");
    DecimalFormat dfLng = new DecimalFormat("#.##");
    DecimalFormat dfZoom = new DecimalFormat("#");
    dfLat.setRoundingMode(RoundingMode.CEILING);
    dfLng.setRoundingMode(RoundingMode.CEILING);
    dfZoom.setRoundingMode(RoundingMode.CEILING);
    double dblLat = Double.parseDouble(dfLat.format(lat));
    double dblLng = Double.parseDouble(dfLng.format(lng));
    double dblZoom = Double.parseDouble(dfZoom.format(zoom));
    //Limit by 1 rows
    Cursor cursor = db.query(DBHelper.LOC_TABLE, null,
            "LAT LIKE '" + dblLat + "%' AND LNG LIKE '" + dblLng + "%' AND ZOOM = '" + dblZoom + "'", null,
            null, null, null, "1");

    int count = cursor.getCount();

    if (count == 0) {
        //user has not been to this location/zoom level  before
        //add the new location data, then trigger the google place webservice api
        ContentValues values = new ContentValues();

        values.put("lat", String.valueOf(dblLat));
        values.put("lng", String.valueOf(dblLng));
        values.put("zoom", String.valueOf(dblZoom));
        db.insert(DBHelper.LOC_TABLE, null, values);

        String url;
        url = updateURL(lat, lng, radius);
        List<List<String>> googlePlaces = null; //null on first reference, the list is updated within the method callstack
        db.close();

        GoogleAPI.callMapMethod(mMap, url, MapsActivity.this, googlePlaces, spinner);
    }
    if (count == 1) {
        //user has been here before
        //get place data from DB and not from the API
        //if place data returned hasn't been updated in 30 days - update data using getPlaceByID method
        Cursor placeCursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_TYPES LIKE '%point_of_interest%'", null,
                null, null, null, null);

        List<List<String>> googlePlaces = new ArrayList<List<String>>();

        while (placeCursor.moveToNext()) {
            String place_ID = placeCursor.getString(placeCursor.getColumnIndex("PLACE_ID"));
            String placeName = placeCursor.getString(placeCursor.getColumnIndex("PLACE_NAME"));
            String placeLoc = placeCursor.getString(placeCursor.getColumnIndex("PLACE_LOCATION"));
            String placeLat = placeCursor.getString(placeCursor.getColumnIndex("LAT"));
            String placeLng = placeCursor.getString(placeCursor.getColumnIndex("LNG"));

            //if lat and long from database is in the search bounds, add to the list of data to be shown
            LatLngBounds SEARCH_BOUNDS = mMap.getProjection().getVisibleRegion().latLngBounds;
            LatLng search_loc = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));

            if (SEARCH_BOUNDS.contains(search_loc)) {
                //now what data do we want?
                //Initiate a place data array
                List<String> placeData = new ArrayList<String>();

                //add place data to its array
                placeData.add(placeName); //0
                placeData.add(place_ID); //1
                placeData.add(placeLoc); //2
                placeData.add(String.valueOf(placeLat)); //3
                placeData.add(String.valueOf(placeLng)); //4
                placeData.add(""); //5
                placeData.add(""); //6

                //send the place specific data to the google places array list
                googlePlaces.add(placeData);
            }
        }
        db.close();

        //TODO: Get this method off the main UI thread!
        GoogleAPI.filterPlaces(googlePlaces, mMap, this, spinner);
    }
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private long getSequence(ImageProperties imp, String accessToken) {
    try {//w w  w. ja  v a  2  s. co m
        URL url = new URL(URL_SEQUENCE);
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST"); // PUT is another valid option
        http.setDoOutput(true);

        DecimalFormat df = new DecimalFormat("#.##############");
        df.setRoundingMode(RoundingMode.CEILING);
        System.out.println("Getting Sequence ID..");
        Map<String, String> arguments = new HashMap<>();
        arguments.put("uploadSource", "OSVUploadr");
        arguments.put("access_token", accessToken);
        arguments.put("currentCoordinate", df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude()));
        System.out.println(
                "currentCoordinate:" + df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude()));
        StringJoiner sj = new StringJoiner("&");
        for (Map.Entry<String, String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
                    + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;
        System.out.println("Sending request:" + sj.toString());

        http.setFixedLengthStreamingMode(length);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        http.connect();
        try (OutputStream os = http.getOutputStream()) {
            os.write(out);
            os.close();
        }
        System.out.println("Request Sent getting sequence response...");
        InputStream is = http.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int letti;

        while ((letti = is.read(buf)) > 0)
            baos.write(buf, 0, letti);

        String data = new String(baos.toByteArray());
        int start = data.indexOf("\"osv\":{\"sequence\":{\"id\":\"");
        int end = data.indexOf("\"", start + 25);
        System.out.println("Received request:" + data);
        String sequence_id = data.substring(start + 25, end);
        System.out.println("Obtained Sequence ID: sequence_id");
        http.disconnect();
        return Long.parseLong(sequence_id);

    } catch (Exception ex) {
        System.out.println(ex.toString());
        Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex);
    }
    return -1;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.CategoricalChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final CategoryPlot cpl = chart.getCategoryPlot();
    final CategoryItemRenderer renderer = cpl.getRenderer();
    if (StringUtils.isEmpty(getTooltipFormula()) == false) {
        renderer.setBaseToolTipGenerator(
                new FormulaCategoryTooltipGenerator(getRuntime(), getTooltipFormula()));
    }/*  w  w  w.j a va  2s .  c om*/
    if (StringUtils.isEmpty(getUrlFormula()) == false) {
        renderer.setBaseItemURLGenerator(new FormulaCategoryURLGenerator(getRuntime(), getUrlFormula()));
    }
    if (this.categoricalLabelFormat != null) {
        final StandardCategoryItemLabelGenerator scilg;
        if (categoricalLabelDecimalFormat != null) {
            final DecimalFormat numFormat = new DecimalFormat(categoricalLabelDecimalFormat,
                    new DecimalFormatSymbols(getRuntime().getResourceBundleFactory().getLocale()));
            numFormat.setRoundingMode(RoundingMode.HALF_UP);
            scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, numFormat);
        } else if (categoricalLabelDateFormat != null) {
            scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, new SimpleDateFormat(
                    categoricalLabelDateFormat, getRuntime().getResourceBundleFactory().getLocale()));
        } else {
            final DecimalFormat formatter = new DecimalFormat();
            formatter.setDecimalFormatSymbols(
                    new DecimalFormatSymbols(getRuntime().getResourceBundleFactory().getLocale()));
            scilg = new StandardCategoryItemLabelGenerator(categoricalLabelFormat, formatter);
        }
        renderer.setBaseItemLabelGenerator(scilg);
    }
    renderer.setBaseItemLabelsVisible(Boolean.TRUE.equals(getItemsLabelVisible()));
    if (getItemLabelFont() != null) {
        renderer.setBaseItemLabelFont(getItemLabelFont());
    }

    if (categoricalItemLabelRotation != null) {
        final ItemLabelPosition orgPosItemLabelPos = renderer.getBasePositiveItemLabelPosition();
        if (orgPosItemLabelPos == null) {
            final ItemLabelPosition pos2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                    TextAnchor.BOTTOM_CENTER, TextAnchor.CENTER, categoricalItemLabelRotation.doubleValue());
            renderer.setBasePositiveItemLabelPosition(pos2);
        } else {
            final ItemLabelPosition pos2 = new ItemLabelPosition(orgPosItemLabelPos.getItemLabelAnchor(),
                    orgPosItemLabelPos.getTextAnchor(), orgPosItemLabelPos.getRotationAnchor(),
                    categoricalItemLabelRotation.doubleValue());
            renderer.setBasePositiveItemLabelPosition(pos2);
        }

        final ItemLabelPosition orgNegItemLabelPos = renderer.getBaseNegativeItemLabelPosition();
        if (orgNegItemLabelPos == null) {
            final ItemLabelPosition pos2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                    TextAnchor.BOTTOM_CENTER, TextAnchor.CENTER, categoricalItemLabelRotation.doubleValue());
            renderer.setBaseNegativeItemLabelPosition(pos2);
        } else {
            final ItemLabelPosition neg2 = new ItemLabelPosition(orgNegItemLabelPos.getItemLabelAnchor(),
                    orgNegItemLabelPos.getTextAnchor(), orgNegItemLabelPos.getRotationAnchor(),
                    categoricalItemLabelRotation.doubleValue());
            renderer.setBaseNegativeItemLabelPosition(neg2);
        }
    }

    final Font labelFont = Font.decode(getLabelFont());

    final CategoryAxis categoryAxis = cpl.getDomainAxis();
    categoryAxis.setLabelFont(labelFont);
    categoryAxis.setTickLabelFont(labelFont);
    if (getCategoryTitleFont() != null) {
        categoryAxis.setLabelFont(getCategoryTitleFont());
    }
    if (getCategoryTickFont() != null) {
        categoryAxis.setTickLabelFont(getCategoryTickFont());
    }

    if (maxCategoryLabelWidthRatio != null) {
        categoryAxis.setMaximumCategoryLabelWidthRatio(maxCategoryLabelWidthRatio.floatValue());
    }
    cpl.setDomainGridlinesVisible(showGridlines);
    if (labelRotation != null) {
        double angle = labelRotation.doubleValue();
        CategoryLabelPosition top = createUpRotationCategoryLabelPosition(PlaneDirection.TOP, angle);
        CategoryLabelPosition bottom = createUpRotationCategoryLabelPosition(PlaneDirection.BOTTOM, angle);
        CategoryLabelPosition left = createUpRotationCategoryLabelPosition(PlaneDirection.LEFT, angle);
        CategoryLabelPosition right = createUpRotationCategoryLabelPosition(PlaneDirection.RIGHT, angle);
        CategoryLabelPositions rotationLabelPositions = new CategoryLabelPositions(top, bottom, left, right);
        categoryAxis.setCategoryLabelPositions(rotationLabelPositions);
    }

    final String[] colors = getSeriesColor();
    for (int i = 0; i < colors.length; i++) {
        renderer.setSeriesPaint(i, parseColorFromString(colors[i]));
    }

    if (lowerMargin != null) {
        categoryAxis.setLowerMargin(lowerMargin.doubleValue());
    }
    if (upperMargin != null) {
        categoryAxis.setUpperMargin(upperMargin.doubleValue());
    }
    if (categoryMargin != null) {
        categoryAxis.setCategoryMargin(categoryMargin.doubleValue());
    }

    configureRangeAxis(cpl, labelFont);
}

From source file:pcgui.SetupParametersPanel.java

/**
 * @param sym//from  ww w.j a va  2 s  .com
 * @param realDist
 */
private String generateIndependentArray(Symbol sym, RealDistribution realDist) {
    ArrayList<Integer> paramValList = new ArrayList<Integer>();
    for (Object param : sym.arrayParams) {
        //extract the dimension
        param = (String) param;
        try {
            Integer val = Integer.parseInt((String) param);
            paramValList.add(val);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            //JOptionPane.showMessageDialog(this,"Check dimension of variable "+sym.name, "Error", JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }

    long arraySize = 1;
    StringBuilder sb = new StringBuilder();
    for (Integer val : paramValList) {
        //         System.out.println("UpdatedParam : "+val);
        arraySize *= val;
    }
    sb.append("[");
    for (long r = 1; r <= arraySize; r++) {
        DecimalFormat df = new DecimalFormat("#.##");
        df.setRoundingMode(RoundingMode.CEILING);
        String val = df.format(realDist.sample());
        sb.append(val);
        sb.append(", ");

    }
    //remove the last ","
    sb.replace(sb.length() - 2, sb.length(), "");
    sb.append("]");
    //      System.out.println("Generated Array: "+ sym.name);
    //      System.out.println(sb.toString());
    return sb.toString();
}

From source file:pcgui.SetupParametersPanel.java

private String generateDependentArray(Symbol sym, RealDistribution realDist) {
    ArrayList<Integer> paramValList = new ArrayList<Integer>();
    for (Object param : sym.arrayParams) {
        //extract the dimension
        param = (String) param;/*from  ww  w .  j av a  2  s  . c  o m*/
        System.out.println("Param name =" + param);
        try {
            if (hashTable.containsKey(param)) {
                Symbol depSym = (Symbol) hashTable.get(param);
                String typeString = depSym.typeString;

                if ("Integer".equalsIgnoreCase(typeString.trim())) {
                    Object strVal = depSym.get();
                    //can only allow allow one more level of dependency
                    //varA Integer varB
                    //ourSym array(varA,varC)
                    if (hashTable.containsKey(strVal)) {
                        Symbol s = (Symbol) hashTable.get(strVal);
                        Integer val = (Integer) s.get();
                        paramValList.add(val);
                    } else {
                        Integer val = (Integer) strVal;
                        paramValList.add(val);
                    }

                } else if ("Set".equalsIgnoreCase(typeString.trim())) {
                    String strVal = (String) depSym.get();
                    if (strVal.contains("..")) {
                        //1..varA
                        //take the upper limit
                        String sizeVar = strVal.split("\\.\\.")[1];
                        if (hashTable.containsKey(sizeVar)) {
                            Symbol s = (Symbol) hashTable.get(sizeVar);
                            //only take the value of this var
                            //not more than 2 level of dependency
                            Integer val = (Integer) s.get();
                            paramValList.add(val);
                        } else {
                            //1..12
                            Integer val = Integer.parseInt((String) sizeVar);
                            paramValList.add(val);
                        }
                    } else {
                        //can only parse simple set size
                        //{A,B,C,D}
                        //{A
                        //B
                        //C
                        //D}
                        //we can get size by splitting using comma ","
                        String strVal2 = (String) depSym.get();
                        Integer val = strVal2.split(",").length;
                        paramValList.add(val);
                    }
                }
            } else {
                //for constant integers
                //ourSym array(varA,5)
                Integer val = Integer.parseInt((String) param);
                paramValList.add(val);
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            //JOptionPane.showMessageDialog(this,"Check dimensions of variable "+sym.name, "Error", JOptionPane.ERROR_MESSAGE);
            return null;
        }
    }

    long arraySize = 1;
    StringBuilder sb = new StringBuilder();
    for (Integer val : paramValList) {
        //         System.out.println("UpdatedParam : "+val);
        arraySize *= val;
    }
    sb.append("[");
    for (long r = 1; r <= arraySize; r++) {
        DecimalFormat df = new DecimalFormat("#.##");
        df.setRoundingMode(RoundingMode.CEILING);
        String val = df.format(realDist.sample());
        sb.append(val);
        sb.append(", ");

    }
    //remove the last ","
    sb.replace(sb.length() - 2, sb.length(), "");
    sb.append("]");
    //      System.out.println("Generated Array: "+ sym.name);
    //      System.out.println(sb.toString());
    return sb.toString();
}

From source file:fr.cls.atoll.motu.library.misc.netcdf.NetCdfReader.java

/**
 * Gets the standard z as string./*  w ww  . j a  v a 2  s.c om*/
 * 
 * @param value the value
 * @param roundingMode the rounding mode
 * @param desiredDecimalNumberDigits the desired decimal number of digits
 * 
 * @return the standard z as fmt string
 */
public static String getStandardZAsString(double value, RoundingMode roundingMode,
        int desiredDecimalNumberDigits) {

    int in = (int) (value);
    double frac = value - in;

    if (frac == 0d) {
        return NetCdfReader.getStandardZAsString(value);
    }

    DecimalFormat decimalFormat = new DecimalFormat();

    decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    decimalFormat.setGroupingUsed(false);
    decimalFormat.setMinimumFractionDigits(desiredDecimalNumberDigits);
    decimalFormat.setMaximumFractionDigits(desiredDecimalNumberDigits);

    decimalFormat.setRoundingMode(roundingMode);

    return decimalFormat.format(value);
}

From source file:io.openvidu.test.e2e.OpenViduTestAppE2eTest.java

private void checkMultimediaFile(File file, boolean hasAudio, boolean hasVideo, double duration,
        String resolution, String audioDecoder, String videoDecoder, boolean checkAudio) throws IOException {
    // Check tracks, duration, resolution, framerate and decoders
    MultimediaFileMetadata metadata = new MultimediaFileMetadata(file.getAbsolutePath());

    if (hasVideo) {
        if (checkAudio) {
            if (hasAudio) {
                Assert.assertTrue("Media file " + file.getAbsolutePath() + " should have audio",
                        metadata.hasAudio() && metadata.hasVideo());
                Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder));
            } else {
                Assert.assertTrue("Media file " + file.getAbsolutePath() + " should have video",
                        metadata.hasVideo());
                Assert.assertFalse(metadata.hasAudio());
            }//  www.j  a  v a  2  s.co  m
        }
        if (resolution != null) {
            Assert.assertEquals(resolution, metadata.getVideoWidth() + "x" + metadata.getVideoHeight());
        }
        Assert.assertTrue(metadata.getVideoDecoder().toLowerCase().contains(videoDecoder));
    } else if (hasAudio && checkAudio) {
        Assert.assertTrue(metadata.hasAudio());
        Assert.assertFalse(metadata.hasVideo());
        Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder));
    } else {
        Assert.fail("Cannot check a file witho no audio and no video");
    }
    // Check duration with 1 decimal precision
    DecimalFormat df = new DecimalFormat("#0.0");
    df.setRoundingMode(RoundingMode.UP);
    log.info("Duration of {} according to ffmpeg: {} s", file.getName(), metadata.getDuration());
    log.info("Duration of {} according to 'duration' property: {} s", file.getName(), duration);
    log.info("Difference in s duration: {}", Math.abs(metadata.getDuration() - duration));
    final double difference = 10;
    Assert.assertTrue("Difference between recording entity duration (" + duration
            + ") and real video duration (" + metadata.getDuration() + ") is greater than " + difference
            + "  in file " + file.getName(), Math.abs((metadata.getDuration() - duration)) < difference);
}