Example usage for java.text DecimalFormat setMinimumIntegerDigits

List of usage examples for java.text DecimalFormat setMinimumIntegerDigits

Introduction

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

Prototype

@Override
public void setMinimumIntegerDigits(int newValue) 

Source Link

Document

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

Usage

From source file:com.itude.mobile.mobbl.core.util.StringUtilities.java

private static void setupFormatter(DecimalFormat formatter, int minumumDecimals, int maximumDecimals) {
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(getDefaultFormattingLocale()));
    formatter.setMinimumIntegerDigits(1);

    if (minumumDecimals > -1) {
        formatter.setMinimumFractionDigits(minumumDecimals);
    }/*from  www  .  j  a v a 2  s.  co m*/
    if (maximumDecimals > -1) {
        formatter.setMaximumFractionDigits(maximumDecimals);
    }
    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
}

From source file:br.com.itfox.utils.Utils.java

public static String formatDecimal(BigDecimal val) {
    String s = "";
    try {/*from w w w  .j a v  a  2  s .  c  o m*/
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale("en", "EN"));
        df.setMaximumFractionDigits(Preferences.MAXIMUM_FRACTION_DIGITS);
        df.setMinimumFractionDigits(Preferences.MINIMUM_FRACTION_DIGITS);
        df.setMinimumIntegerDigits(Preferences.MIMIMUM_INTEGER_DIGITS);
        df.setRoundingMode(Preferences.ROUNDING_MODE);
        s = String.valueOf(df.format(val));
    } catch (Exception ex) {
        br.com.itfox.utils.Logger.getLogger(ex, Utils.class.getName() + "***" + val + "***", ex.getMessage());
    }
    return s;

}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static void analyseWaitTimes(String fileName, List<DynModeTrip> trips, int binsize_s) {
    Collections.sort(trips);/*from   ww w  .j  a va  2 s  .  c om*/
    if (trips.size() == 0)
        return;
    int startTime = ((int) (trips.get(0).getDepartureTime() / binsize_s)) * binsize_s;
    int endTime = ((int) (trips.get(trips.size() - 1).getDepartureTime() / binsize_s) + binsize_s) * binsize_s;
    Map<Double, List<DynModeTrip>> splitTrips = splitTripsIntoBins(trips, startTime, endTime, binsize_s);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

    BufferedWriter bw = IOUtils.getBufferedWriter(fileName + ".csv");
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeriesCollection datasetrequ = new TimeSeriesCollection();
    TimeSeries averageWaitC = new TimeSeries("average");
    TimeSeries medianWait = new TimeSeries("median");
    TimeSeries p_5Wait = new TimeSeries("5th percentile");
    TimeSeries p_95Wait = new TimeSeries("95th percentile");
    TimeSeries requests = new TimeSeries("Ride requests");

    try {
        bw.write("timebin;trips;average_wait;min;p_5;p_25;median;p_75;p_95;max");
        for (Entry<Double, List<DynModeTrip>> e : splitTrips.entrySet()) {
            long rides = 0;
            double averageWait = 0;
            double min = 0;
            double p_5 = 0;
            double p_25 = 0;
            double median = 0;
            double p_75 = 0;
            double p_95 = 0;
            double max = 0;
            if (!e.getValue().isEmpty()) {
                DescriptiveStatistics stats = new DescriptiveStatistics();
                for (DynModeTrip t : e.getValue()) {
                    stats.addValue(t.getWaitTime());
                }
                rides = stats.getN();
                averageWait = stats.getMean();
                min = stats.getMin();
                p_5 = stats.getPercentile(5);
                p_25 = stats.getPercentile(25);
                median = stats.getPercentile(50);
                p_75 = stats.getPercentile(75);
                p_95 = stats.getPercentile(95);
                max = stats.getMax();

            }
            Minute h = new Minute(sdf2.parse(Time.writeTime(e.getKey())));

            medianWait.addOrUpdate(h, Double.valueOf(median));
            averageWaitC.addOrUpdate(h, Double.valueOf(averageWait));
            p_5Wait.addOrUpdate(h, Double.valueOf(p_5));
            p_95Wait.addOrUpdate(h, Double.valueOf(p_95));
            requests.addOrUpdate(h, rides * 3600. / binsize_s);// normalised [req/h]
            bw.newLine();
            bw.write(Time.writeTime(e.getKey()) + ";" + rides + ";" + format.format(averageWait) + ";"
                    + format.format(min) + ";" + format.format(p_5) + ";" + format.format(p_25) + ";"
                    + format.format(median) + ";" + format.format(p_75) + ";" + format.format(p_95) + ";"
                    + format.format(max));

        }
        bw.flush();
        bw.close();
        dataset.addSeries(averageWaitC);
        dataset.addSeries(medianWait);
        dataset.addSeries(p_5Wait);
        dataset.addSeries(p_95Wait);
        datasetrequ.addSeries(requests);
        JFreeChart chart = chartProfile(splitTrips.size(), dataset, "Waiting times", "Wait time (s)");
        JFreeChart chart2 = chartProfile(splitTrips.size(), datasetrequ, "Ride requests per hour",
                "Requests per hour (req/h)");
        ChartSaveUtils.saveAsPNG(chart, fileName, 1500, 1000);
        ChartSaveUtils.saveAsPNG(chart2, fileName + "_requests", 1500, 1000);

    } catch (IOException | ParseException e) {

        e.printStackTrace();
    }

}

From source file:br.com.itfox.utils.Utils.java

public static String formatDecimal(float val) {
    String s = "";
    if (val > 0) {
        try {/*  ww  w.  j  a va 2  s .com*/
            DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale("en", "EN"));
            df.setMaximumFractionDigits(Preferences.MAXIMUM_FRACTION_DIGITS);
            df.setMinimumFractionDigits(Preferences.MINIMUM_FRACTION_DIGITS);
            df.setMinimumIntegerDigits(Preferences.MIMIMUM_INTEGER_DIGITS);
            df.setRoundingMode(Preferences.ROUNDING_MODE);
            s = String.valueOf(df.format(val));
        } catch (Exception ex) {
            br.com.itfox.utils.Logger.getLogger(ex, Utils.class.getName() + "***" + val + "***",
                    ex.getMessage());
        }
    }
    return s;

}

From source file:br.com.itfox.utils.Utils.java

public static String formatDecimal(double val) {
    String s = "";
    if (val > 0) {
        try {/*from   w  w  w .  j  a v a  2  s.  c  o m*/
            DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale("en", "EN"));
            df.setMaximumFractionDigits(Preferences.MAXIMUM_FRACTION_DIGITS);
            df.setMinimumFractionDigits(Preferences.MINIMUM_FRACTION_DIGITS);
            df.setMinimumIntegerDigits(Preferences.MIMIMUM_INTEGER_DIGITS);
            df.setRoundingMode(Preferences.ROUNDING_MODE);
            s = String.valueOf(df.format(val));
        } catch (Exception ex) {
            br.com.itfox.utils.Logger.getLogger(ex, Utils.class.getName() + "***" + val + "***",
                    ex.getMessage());
        }
    }
    return s;

}

From source file:org.mitre.ccv.mapred.CalculateCosineDistanceMatrix.java

/**
 * Writes out the matrix in row major (packed) order. No labels are outputed.
 *
 * @param jobConf/*from  ww  w .  j a va 2  s  .  c om*/
 * @param input
 * @param output
 * @param digits
 * @throws IOException
 */
public static void printRowMajorMatrix(JobConf jobConf, String input, String output, int digits)
        throws IOException {
    JobConf conf = new JobConf(jobConf, CalculateCosineDistanceMatrix.class);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(digits);
    //format.setMinimumFractionDigits(fractionDigits);
    format.setGroupingUsed(false);

    final Path inputPath = new Path(input);
    final FileSystem fs = inputPath.getFileSystem(conf);
    final Path qInputPath = fs.makeQualified(inputPath);
    final Path outputPath = new Path(output);
    Path[] paths = FileUtils.ls(conf, qInputPath.toString() + Path.SEPARATOR + "part-*");

    FSDataOutputStream fos = fs.create(outputPath, true); // throws nothing!
    final Writer writer = new OutputStreamWriter(fos);
    final Text key = new Text();
    final DenseVectorWritable value = new DenseVectorWritable();
    for (int idx = 0; idx < paths.length; idx++) {
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, paths[idx], conf);
        boolean hasNext = reader.next(key, value);
        while (hasNext) {

            final DenseVector vector = value.get();
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < vector.getCardinality(); i++) {
                final String s = format.format(vector.get(i)); // format the number
                sb.append(s);
                sb.append(' ');
            }
            writer.write(sb.toString());
            hasNext = reader.next(key, value);
        }
        try {
            writer.flush();
            reader.close();
        } catch (IOException ioe) {
            // closing the SequenceFile.Reader will throw an exception if the file is over some unknown size
            LOG.debug("Probably caused by closing the SequenceFile.Reader. All is well", ioe);
        }
    }
    try {
        writer.close();
        fos.flush();
        fos.close();
    } catch (IOException ioe) {
        LOG.debug("Caused by distributed cache output stream.", ioe);
    }
}

From source file:org.mitre.ccv.mapred.CalculateCosineDistanceMatrix.java

/**
 * Outputs the distance matrix (DenseVectors) in Phylip Square format. Names/labels are limited to 10-characters!
 *
 * @param jobConf/*from  ww w  .j  a v a 2s  .c o  m*/
 * @param input             input directory name containing DenseVectors (as generated by this class).
 * @param output            output file name
 * @param fractionDigits    number of digits after decimal point
 * @throws IOException
 */
public static void printPhylipSquare(JobConf jobConf, String input, String output, int fractionDigits)
        throws IOException {
    JobConf conf = new JobConf(jobConf, CalculateCosineDistanceMatrix.class);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(fractionDigits);
    //format.setMinimumFractionDigits(fractionDigits);
    format.setGroupingUsed(false);

    final Path inputPath = new Path(input);
    final FileSystem fs = inputPath.getFileSystem(conf);
    final Path qInputPath = fs.makeQualified(inputPath);
    final Path outputPath = new Path(output);
    Path[] paths = FileUtils.ls(conf, qInputPath.toString() + Path.SEPARATOR + "part-*");

    FSDataOutputStream fos = fs.create(outputPath, true); // throws nothing!
    Writer writer = new OutputStreamWriter(fos);
    Text key = new Text();
    DenseVectorWritable value = new DenseVectorWritable();
    Boolean wroteHeader = false;
    for (int idx = 0; idx < paths.length; idx++) {
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, paths[idx], conf);
        boolean hasNext = reader.next(key, value);
        while (hasNext) {

            final DenseVector vector = value.get();
            if (!wroteHeader) {
                writer.write(String.format("\t%d\n", vector.getCardinality()));
                wroteHeader = true;
            }

            final StringBuilder sb = new StringBuilder();
            final String name = key.toString();
            sb.append(name.substring(0, (name.length() > 10 ? 10 : name.length())));
            final int padding = Math.max(1, 10 - name.length());
            for (int k = 0; k < padding; k++) {
                sb.append(' ');
            }
            sb.append(' ');
            for (int i = 0; i < vector.getCardinality(); i++) {
                final String s = format.format(vector.get(i)); // format the number
                sb.append(s);
                sb.append(' ');
            }
            sb.append("\n");
            writer.write(sb.toString());
            hasNext = reader.next(key, value);
        }
        try {
            writer.flush();
            reader.close();
        } catch (IOException ioe) {
            // closing the SequenceFile.Reader will throw an exception if the file is over some unknown size
            LOG.debug("Probably caused by closing the SequenceFile.Reader. All is well", ioe);
        }
    }
    try {
        writer.close();
        fos.flush();
        fos.close();
    } catch (IOException ioe) {
        LOG.debug("Caused by distributed cache output stream.", ioe);
    }
}

From source file:com.itude.mobile.android.util.StringUtil.java

/**
 * Set the formatter.//from  w  w w  . j av  a 2 s. c o  m
 * 
 * @param formatter {@link DecimalFormat}
 * @param locale {@link Locale}
 * @param minimalDecimalNumbers minimal number of decimals
 * @param maximumDecimalNumbers maximum number of decimals
 */
private static void setupFormatter(DecimalFormat formatter, Locale locale, int minimalDecimalNumbers,
        int maximumDecimalNumbers) {
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
    formatter.setMinimumIntegerDigits(1);
    formatter.setMinimumFractionDigits(minimalDecimalNumbers);
    formatter.setMaximumFractionDigits(maximumDecimalNumbers);
    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
}

From source file:com.sforce.dataset.DatasetUtilMain.java

public static String getActionFromUser() {
    System.out.println();/*  w  ww .  j a va 2  s  . c om*/
    String selectedAction = "load";
    DecimalFormat df = new DecimalFormat("00");
    df.setMinimumIntegerDigits(2);
    int cnt = 1;
    for (String[] action : validActions) {
        if (cnt == 1)
            System.out.println("Available Datasetutil Actions: ");
        System.out.print(" ");
        System.out.println(DatasetUtils.padLeft(cnt + "", 3) + ". " + action[1]);
        cnt++;
    }
    System.out.println();

    while (true) {
        try {
            String tmp = DatasetUtils.readInputFromConsole("Enter Action number (0  = Exit): ");
            if (tmp == null)
                return null;
            if (tmp.trim().isEmpty())
                continue;
            long choice = Long.parseLong(tmp.trim());
            if (choice == 0)
                return null;
            cnt = 1;
            if (choice > 0 && choice <= validActions.length) {
                for (String[] action : validActions) {
                    if (cnt == choice) {
                        selectedAction = action[0];
                        return selectedAction;
                    }
                    cnt++;
                }
            }
        } catch (Throwable me) {
        }
    }
}

From source file:org.mitre.math.linear.RandomMatrixExample.java

/**
 * /*from w ww .ja  v a2s  .  co  m*/
 * @param m
 * @param width      Column width.
 * @param digits     Number of digits after the decimal.
 * @return
 */
public String matrix2String(RealMatrix m, int width, int digits) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(digits);
    format.setMinimumFractionDigits(digits);
    format.setGroupingUsed(false);

    StringBuilder output = new StringBuilder();
    output.append('\n'); // start on new line.
    for (int i = 0; i < m.getRowDimension(); i++) {
        for (int j = 0; j < m.getColumnDimension(); j++) {
            String s = format.format(m.getEntry(i, j)); // format the number
            int padding = Math.max(1, width - s.length()); // At _least_ 1 space
            for (int k = 0; k < padding; k++) {
                output.append(' ');
            }
            output.append(s);
        }
        output.append('\n');
    }
    output.append('\n'); // end with blank line.
    return output.toString();
}