Example usage for java.text DecimalFormat DecimalFormat

List of usage examples for java.text DecimalFormat DecimalFormat

Introduction

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

Prototype

public DecimalFormat(String pattern) 

Source Link

Document

Creates a DecimalFormat using the given pattern and the symbols for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:net.jarcec.sqoop.data.gen.mr.GeneratorMapper.java

@Override
protected void map(LongWritable key, LongWritable value, Context context)
        throws IOException, InterruptedException {
    long from = key.get();
    long to = value.get();

    random = new SecureRandom();
    decimal = new DecimalFormat("###.###");
    date = new SimpleDateFormat("yyyy-MM-dd");
    time = new SimpleDateFormat("HH:mm:ss");
    datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String[] types = context.getConfiguration().get(Constants.TYPES).split(",");
    String[] values = new String[types.length];

    for (long i = from; i < to; i++) {
        context.progress();/*from  w  w  w .  j  a v  a2 s  . com*/

        int y = 0;
        for (String type : types) {

            if ("id".equals(type)) {
                values[y] = String.valueOf(i);
            } else if ("s50".equals(type)) {
                values[y] = generateString(50);
            } else if ("i".equals(type)) {
                values[y] = generateInteger();
            } else if ("f".equals(type)) {
                values[y] = generateFloat(250, 31);
            } else if ("d".equals(type)) {
                values[y] = generateDate();
            } else if ("t".equals(type)) {
                values[y] = generateTime();
            } else if ("dt".equals(type)) {
                values[y] = generateDateTime();
            } else if ("s255".equals(type)) {
                values[y] = generateString(255);
            } else {
                throw new RuntimeException("Unknown type: " + type);
            }

            y++;
        }

        context.write(new Text(StringUtils.join(values, ",")), NullWritable.get());
    }
}

From source file:elaborate.editor.backend.AnnotationMarkerScrubber.java

private static String percentage(int part, int total) {
    return new DecimalFormat("0.00").format((double) (100 * part) / (double) total);
}

From source file:matrix.CreateTextMatrix.java

public void textMatrix()
        throws UnsupportedEncodingException, FileNotFoundException, IOException, ParseException {

    CosSim cossim = new CosSim();
    JSONParser jParser = new JSONParser();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            new FileInputStream("/Users/nSabri/Desktop/tweetMatris/userTweets.json"), "ISO-8859-9"));
    JSONArray a = (JSONArray) jParser.parse(in);
    File fout = new File("/Users/nSabri/Desktop/tweetMatris.csv");
    FileOutputStream fos = new FileOutputStream(fout);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    for (int i = 0; i < 1000; i++) {

        for (int j = 0; j < 1000; j++) {

            JSONObject tweet1 = (JSONObject) a.get(i);
            JSONObject tweet2 = (JSONObject) a.get(j);
            String tweetText1 = tweet1.get("tweets").toString();
            String tweetText2 = tweet2.get("tweets").toString();

            double CosSimValue = cossim.Cosine_Similarity_Score(tweetText1, tweetText2);
            CosSimValue = Double.parseDouble(new DecimalFormat("##.###").format(CosSimValue));
            bw.write(Double.toString(CosSimValue) + ", ");

        }//from   w  w w.ja  va  2  s . c  om
        bw.newLine();
    }
    bw.close();

}

From source file:mase.me.MEGenerationalStat.java

@Override
public void postBreedingStatistics(EvolutionState state) {
    super.postBreedingStatistics(state);
    MESubpopulation pop = (MESubpopulation) state.population.subpops[0];
    DescriptiveStatistics fit = new DescriptiveStatistics();
    for (Individual ind : pop.map.values()) {
        fit.addValue(((ExpandedFitness) ind.fitness).getFitnessScore());
    }//from  ww  w . j a  v a2  s . c  o m
    state.output.println(state.generation + " " + pop.map.keySet().size() + " " + pop.map.size() + " "
            + fit.getMin() + " " + fit.getMean() + " " + fit.getMax() + " " + pop.newInRepo, log);
    state.output.message("Repertoire size: " + pop.map.keySet().size() + " | New: " + pop.newInRepo
            + " | Avg. fitness: " + new DecimalFormat("0.0000").format(fit.getMean()));
}

From source file:c.depthchart.ViewerPanel.java

public ViewerPanel() {
    setBackground(Color.WHITE);/*from  w  w  w. j  a v  a2 s  .co m*/

    df = new DecimalFormat("0.#"); // 1 dp
    msgFont = new Font("SansSerif", Font.BOLD, 18);

    initChart();
    configOpenNI();

    histogram = new float[MAX_DEPTH_SIZE];

    imWidth = depthMD.getFullXRes();
    imHeight = depthMD.getFullYRes();
    System.out.println("Image dimensions (" + imWidth + ", " + imHeight + ")");

    // create empty image object of correct size and type
    imgbytes = new byte[imWidth * imHeight];
    image = new BufferedImage(imWidth, imHeight, BufferedImage.TYPE_BYTE_GRAY);

    new Thread(this).start(); // start updating the panel's image
}

From source file:edu.wpi.checksims.algorithm.similaritymatrix.output.MatrixToCSVPrinter.java

/**
 * Print a Similarity Matrix in CSV format.
 *
 * @param matrix Matrix to print//ww  w  .ja va  2  s.  com
 * @return CSV representation of matrix
 * @throws InternalAlgorithmError Thrown on internal error processing matrix
 */
@Override
public String printMatrix(SimilarityMatrix matrix) throws InternalAlgorithmError {
    checkNotNull(matrix);

    StringBuilder builder = new StringBuilder();
    DecimalFormat formatter = new DecimalFormat("0.00");

    Pair<Integer, Integer> arrayBounds = matrix.getArrayBounds();

    // First row: NULL, then all the Y submissions, comma-separated
    builder.append("NULL,");
    for (int y = 0; y < arrayBounds.getRight(); y++) {
        builder.append("\"");
        builder.append(matrix.getYSubmission(y).getName());
        builder.append("\"");
        if (y != (arrayBounds.getRight() - 1)) {
            builder.append(",");
        } else {
            builder.append("\n");
        }
    }

    // Remaining rows: X label, then all Y results in order
    for (int x = 0; x < arrayBounds.getLeft(); x++) {
        // First, append name of the X submission
        builder.append("\"");
        builder.append(matrix.getXSubmission(x).getName());
        builder.append("\",");

        // Next, append all the matrix values, formatted as given
        for (int y = 0; y < arrayBounds.getRight(); y++) {
            builder.append(formatter.format(matrix.getEntryFor(x, y).getSimilarityPercent()));
            if (y != (arrayBounds.getRight() - 1)) {
                builder.append(",");
            } else {
                builder.append("\n");
            }
        }
    }

    return builder.toString();
}

From source file:Coordinate.java

/**
 * Constructor for this class//from www  .j  ava 2s .  c om
 *
 * @param latitude a latitude coordinate in decimal notation
 * @param longitude a longitude coordinate in decimal notation
 */
public Coordinate(float latitude, float longitude) {

    if (CoordinateManager.isValidLatitude(latitude) == true
            && CoordinateManager.isValidLongitude(longitude) == true) {
        this.latitude = latitude;
        this.longitude = longitude;
    } else {
        throw new IllegalArgumentException(
                "The parameters did not pass validation as defined by the CoordinateManager class");
    }

    this.format = new DecimalFormat("##.######");
}

From source file:org.esupportail.papercut.domain.UserPapercutInfos.java

/**
 * Papercut WebService gives balance values like 1.9465000000000003 
 * Error of epsilon machine is suspected in Papercut !
 * -> to workaround, we simply here round the balance ... 
 * //from  ww  w .  j a v  a  2  s .c  o m
 * Note that 5 decimals is the max in papercut today, but maybe one day it will be more so here we return with 10 max 
 * 
 * @param balance
 * @return
 */
private static String fixRoundPapercutError(String balance) {
    DecimalFormat df = new DecimalFormat("#.##########");
    df.setRoundingMode(RoundingMode.HALF_UP);
    return df.format(Double.valueOf(balance));
}

From source file:com.nikolak.weatherapp.ForecastIO.Currently.java

public String getPrecipIntensity() {
    return new DecimalFormat("#.##").format(this.precipIntensity);
}

From source file:com.polivoto.logica.RecibirVotos.java

public void actualizarConteo(int personasQueHanVotado) {
    /*/* w w w  .  j a  v  a  2s.c  o m*/
    * Porcentaje
    */
    if (votos >= poblacion)
        poblacion = votos = personasQueHanVotado;
    else
        votos = personasQueHanVotado;
    lblvotos_totales.setText(String.valueOf(personasQueHanVotado));
    porcentaje = (votos * 100) / (poblacion == 0 ? 1 : poblacion);
    if (porcentaje >= 100.0 || (porcentaje % 1) == 0)
        decimales = new DecimalFormat("0");
    else
        decimales = new DecimalFormat("0.00");
    lblporcentaje.setText("" + decimales.format(porcentaje) + "%");

    // Fuente de Datos
    data = new DefaultPieDataset();
    data.setValue("SI", votos);
    data.setValue("NO", poblacion - votos);
    // Creando el Grafico
    chart = ChartFactory.createPieChart("", data, false, false, false);
    chart.setBackgroundPaint(Color.white);

    plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setLabelGenerator(null);
    plot.setOutlineVisible(false);
    plot.setSectionPaint("SI", new Color(0, 204, 0));
    plot.setSectionPaint("NO", new Color(218, 24, 24));

    // Crear el Panel del Grafico con ChartPanel
    chartPanel = new ChartPanel(chart, 161, 131, 161, 131, 161, 131, false, false, false, false, false, false);
    chartPanel.setEnabled(false);
    pnlgrafica.setLayout(new java.awt.BorderLayout());
    pnlgrafica.removeAll();
    pnlgrafica.add(chartPanel, BorderLayout.CENTER);
    pnlgrafica.validate();
}