Example usage for java.text DecimalFormat setMaximumFractionDigits

List of usage examples for java.text DecimalFormat setMaximumFractionDigits

Introduction

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

Prototype

@Override
public void setMaximumFractionDigits(int newValue) 

Source Link

Document

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

Usage

From source file:daylightchart.daylightchart.calculation.RiseSetUtility.java

/**
 * Debug calculations.//from   ww w. jav  a2  s  .  c o  m
 *
 * @param writer
 *        Writer to write to
 * @param location
 *        Location to debug
 * @param daylightBandType
 *        Types of band type to write to
 */
@SuppressWarnings("boxing")
private static void writeCalculations(final Writer writer, final Location location, final TwilightType twilight,
        final DaylightBandType... daylightBandType) {
    if (writer == null || location == null) {
        return;
    }

    final DecimalFormat format = new DecimalFormat("00.000");
    format.setMaximumFractionDigits(3);

    final int year = Year.now().getValue();
    final Options options = new Options();
    options.setTwilightType(twilight);
    final RiseSetYearData riseSetYear = createRiseSetYear(location, year, options);

    final PrintWriter printWriter = new PrintWriter(writer, true);
    // Header
    printWriter.printf("Location\t%s%nDate\t%s%n%n", location, year);
    // Bands
    final List<DaylightBand> bands = riseSetYear.getBands();
    for (final Iterator<DaylightBand> iterator = bands.iterator(); iterator.hasNext();) {
        final DaylightBand band = iterator.next();
        if (!ArrayUtils.contains(daylightBandType, band.getDaylightBandType())) {
            iterator.remove();
        }
    }
    printWriter.printf("\t\t\t");
    if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) {
        printWriter.printf("\t\t");
    }
    for (final DaylightBand band : bands) {
        printWriter.printf("Band\t%s\t", band.getName());
    }
    printWriter.println();
    // Data rows
    printWriter.print("Date\tSunrise\tSunset");
    if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) {
        printWriter.println("\tTwilight Rise\tTwilight Set");
    } else {
        printWriter.println();
    }
    final List<RawRiseSet> rawRiseSets = riseSetYear.getRawRiseSets();
    final List<RawRiseSet> rawTwilights = riseSetYear.getRawTwilights();
    for (int i = 0; i < rawRiseSets.size(); i++) {
        final RawRiseSet rawRiseSet = rawRiseSets.get(i);
        printWriter.printf("%s\t%s\t%s", rawRiseSet.getDate(), format.format(rawRiseSet.getSunrise()),
                format.format(rawRiseSet.getSunset()));
        if (ArrayUtils.contains(daylightBandType, DaylightBandType.twilight)) {
            final RawRiseSet rawTwilight = rawTwilights.get(i);
            printWriter.printf("\t%s\t%s", format.format(rawTwilight.getSunrise()),
                    format.format(rawTwilight.getSunset()));
        }
        for (final DaylightBand band : bands) {
            final RiseSet riseSet = band.get(rawRiseSet.getDate());
            if (riseSet == null) {
                printWriter.print("\t\t");
            } else {
                printWriter.printf("\t%s\t%s",
                        riseSet.getSunrise().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
                        riseSet.getSunset().toLocalTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            }
        }
        printWriter.println();
    }
}

From source file:org.renjin.base.StrSignIf.java

private static NumberFormat buildFormat(int digits, String format, String flag) {
    if (format.equals("d")) {
        return NumberFormat.getIntegerInstance();
    } else {/*from  w ww.  j a  va 2 s  .com*/

        DecimalFormat formatter;
        if (format.equals("e")) {
            formatter = new DecimalFormat("0.00e0");
        } else if (format.equals("E")) {
            formatter = new DecimalFormat("0.00E0");
        } else {
            formatter = new DecimalFormat();
        }
        if (digits < 0) {
            digits = 6;
        }
        formatter.setMaximumFractionDigits(digits);
        formatter.setMinimumFractionDigits(digits);
        return formatter;
    }
}

From source file:com.nubits.nubot.utils.Utils.java

public static String formatNumber(double number, int digits) {
    DecimalFormat df = new DecimalFormat("0");
    df.setMaximumFractionDigits(digits);
    return df.format(number);
}

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

public static String summarizeDetailedOccupancyStats(Map<Id<Vehicle>, double[]> vehicleDistances, String del,
        int maxcap) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);/*from w  w  w.j  ava 2 s  . c  om*/
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    double[] sum = new double[maxcap + 1];

    for (double[] dist : vehicleDistances.values()) {
        double emptyD = dist[0] - dist[2];
        sum[0] += emptyD;
        for (int i = 3; i < maxcap + 3; i++) {
            sum[i - 2] += dist[i];
        }
    }
    String result = "";
    for (int i = 0; i <= maxcap; i++) {
        result = result + ";" + format.format(sum[i]);
    }

    return result;
}

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

/**
 * @param vehicleDistances/*from   www.ja v  a2 s . c om*/
 * @param string
 * @return
 */
public static String summarizeVehicles(Map<Id<Vehicle>, double[]> vehicleDistances, String del) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    DescriptiveStatistics driven = new DescriptiveStatistics();
    DescriptiveStatistics revenue = new DescriptiveStatistics();
    DescriptiveStatistics occupied = new DescriptiveStatistics();
    DescriptiveStatistics empty = new DescriptiveStatistics();

    for (double[] dist : vehicleDistances.values()) {
        driven.addValue(dist[0]);
        revenue.addValue(dist[1]);
        occupied.addValue(dist[2]);
        double emptyD = dist[0] - dist[2];
        empty.addValue(emptyD);
    }
    double d_r_d_t = revenue.getSum() / driven.getSum();
    // bw.write("iteration;vehicles;totalDistance;totalEmptyDistance;emptyRatio;totalRevenueDistance;averageDrivenDistance;averageEmptyDistance;averageRevenueDistance");
    String result = vehicleDistances.size() + del + format.format(driven.getSum()) + del
            + format.format(empty.getSum()) + del + format.format(empty.getSum() / driven.getSum()) + del
            + format.format(revenue.getSum()) + del + format.format(driven.getMean()) + del
            + format.format(empty.getMean()) + del + format.format(revenue.getMean()) + del
            + format.format(d_r_d_t);
    return result;
}

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

/**
 * @param vehicleDistances/*from   w  ww .j  a  va 2 s.  com*/
 * @param iterationFilename
 */
public static void writeVehicleDistances(Map<Id<Vehicle>, double[]> vehicleDistances,
        String iterationFilename) {
    String header = "vehicleId;drivenDistance_m;occupiedDistance_m;emptyDistance_m;revenueDistance_pm";
    BufferedWriter bw = IOUtils.getBufferedWriter(iterationFilename);
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);
    try {
        bw.write(header);
        for (Entry<Id<Vehicle>, double[]> e : vehicleDistances.entrySet()) {
            double drivenDistance = e.getValue()[0];
            double revenueDistance = e.getValue()[1];
            double occDistance = e.getValue()[2];
            double emptyDistance = drivenDistance - occDistance;
            bw.newLine();
            bw.write(e.getKey().toString() + ";" + format.format(drivenDistance) + ";"
                    + format.format(occDistance) + ";" + format.format(emptyDistance) + ";"
                    + format.format(revenueDistance));
        }
        bw.flush();
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

public static String summarizeTrips(List<DynModeTrip> trips, String delimiter) {
    DescriptiveStatistics waitStats = new DescriptiveStatistics();
    DescriptiveStatistics rideStats = new DescriptiveStatistics();
    DescriptiveStatistics distanceStats = new DescriptiveStatistics();
    DescriptiveStatistics directDistanceStats = new DescriptiveStatistics();

    DescriptiveStatistics traveltimes = new DescriptiveStatistics();

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);//from  ww w.  j a  va 2s.  c o m
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    for (DynModeTrip trip : trips) {
        if (trip.getToLinkId() == null) {
            continue;
        }
        waitStats.addValue(trip.getWaitTime());
        rideStats.addValue(trip.getInVehicleTravelTime());
        distanceStats.addValue(trip.getTravelDistance());
        directDistanceStats.addValue(trip.getUnsharedDistanceEstimate_m());
        traveltimes.addValue(trip.getInVehicleTravelTime() + trip.getWaitTime());
    }
    String value = format.format(waitStats.getValues().length) + delimiter + format.format(waitStats.getMean())
            + delimiter + format.format(waitStats.getMax()) + delimiter
            + format.format(waitStats.getPercentile(95)) + delimiter
            + format.format(waitStats.getPercentile(75)) + delimiter
            + format.format(waitStats.getPercentile(50)) + delimiter + format.format(rideStats.getMean())
            + delimiter + format.format(distanceStats.getMean()) + delimiter
            + format.format(directDistanceStats.getMean()) + delimiter + format.format(traveltimes.getMean());
    return value;
}

From source file:org.onebusaway.nyc.presentation.impl.realtime.SiriSupport.java

private static OnwardCallStructure getOnwardCallStructure(StopBean stopBean,
        PresentationService presentationService, double distanceOfCallAlongTrip,
        double distanceOfVehicleFromCall, int visitNumber, int index, TimepointPredictionRecord prediction,
        long responseTimestamp) {

    OnwardCallStructure onwardCallStructure = new OnwardCallStructure();
    onwardCallStructure.setVisitNumber(BigInteger.valueOf(visitNumber));

    StopPointRefStructure stopPointRef = new StopPointRefStructure();
    stopPointRef.setValue(stopBean.getId());
    onwardCallStructure.setStopPointRef(stopPointRef);

    NaturalLanguageStringStructure stopPoint = new NaturalLanguageStringStructure();
    stopPoint.setValue(stopBean.getName());
    onwardCallStructure.setStopPointName(stopPoint);

    if (prediction != null) {
        if (prediction.getTimepointPredictedTime() < responseTimestamp) {
            onwardCallStructure.setExpectedArrivalTime(new Date(responseTimestamp));
            onwardCallStructure.setExpectedDepartureTime(new Date(responseTimestamp));
        } else {/*from   w ww .j a  v a  2s . co m*/
            onwardCallStructure.setExpectedArrivalTime(new Date(prediction.getTimepointPredictedTime()));
            onwardCallStructure.setExpectedDepartureTime(new Date(prediction.getTimepointPredictedTime()));
        }
    }

    // siri extensions
    SiriExtensionWrapper wrapper = new SiriExtensionWrapper();
    ExtensionsStructure distancesExtensions = new ExtensionsStructure();
    SiriDistanceExtension distances = new SiriDistanceExtension();

    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    df.setGroupingUsed(false);

    distances.setStopsFromCall(index);
    distances.setCallDistanceAlongRoute(Double.valueOf(df.format(distanceOfCallAlongTrip)));
    distances.setDistanceFromCall(Double.valueOf(df.format(distanceOfVehicleFromCall)));
    distances.setPresentableDistance(presentationService.getPresentableDistance(distances));

    wrapper.setDistances(distances);
    distancesExtensions.setAny(wrapper);
    onwardCallStructure.setExtensions(distancesExtensions);

    return onwardCallStructure;
}

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

/**
 * Writes out the {@link SequenceFile} feature vectors in row major (packed) order. No labels are outputed.
 *
 * @param jobConf/* w  ww .j a  v a 2 s  .  c  o  m*/
 * @param input     top level SequenceFile directory path
 * @param output    path to output the matrix
 * @param digits    the maximum number of fraction digits
 * @throws IOException
 */
public static void featureVectors2RowMajorMatrix(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 SparseVectorWritable value = new SparseVectorWritable();
    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 SparseVector 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.onebusaway.nyc.presentation.impl.realtime.SiriSupport.java

private static MonitoredCallStructure getMonitoredCallStructure(StopBean stopBean,
        PresentationService presentationService, double distanceOfCallAlongTrip,
        double distanceOfVehicleFromCall, int visitNumber, int index, TimepointPredictionRecord prediction,
        long responseTimestamp) {

    MonitoredCallStructure monitoredCallStructure = new MonitoredCallStructure();
    monitoredCallStructure.setVisitNumber(BigInteger.valueOf(visitNumber));

    StopPointRefStructure stopPointRef = new StopPointRefStructure();
    stopPointRef.setValue(stopBean.getId());
    monitoredCallStructure.setStopPointRef(stopPointRef);

    NaturalLanguageStringStructure stopPoint = new NaturalLanguageStringStructure();
    stopPoint.setValue(stopBean.getName());
    monitoredCallStructure.setStopPointName(stopPoint);

    if (prediction != null) {
        // do not allow predicted times to be less than ResponseTimestamp
        if (prediction.getTimepointPredictedTime() < responseTimestamp) {
            /*/*from  w  ww .j  a  v a  2 s  .c  o  m*/
             * monitoredCall has less precision than onwardCall (date vs. timestamp)
             * which results in a small amount of error when converting back to timestamp.
             * Add a second here to prevent negative values from showing up in the UI 
             * (actual precision of the value is 1 minute, so a second has little influence)
             */
            monitoredCallStructure.setExpectedArrivalTime(new Date(responseTimestamp + 1000));
            monitoredCallStructure.setExpectedDepartureTime(new Date(responseTimestamp + 1000));
        } else {
            monitoredCallStructure.setExpectedArrivalTime(new Date(prediction.getTimepointPredictedTime()));
            monitoredCallStructure.setExpectedDepartureTime(new Date(prediction.getTimepointPredictedTime()));
        }

    }

    // siri extensions
    SiriExtensionWrapper wrapper = new SiriExtensionWrapper();
    ExtensionsStructure distancesExtensions = new ExtensionsStructure();
    SiriDistanceExtension distances = new SiriDistanceExtension();

    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    df.setGroupingUsed(false);

    distances.setStopsFromCall(index);
    distances.setCallDistanceAlongRoute(Double.valueOf(df.format(distanceOfCallAlongTrip)));
    distances.setDistanceFromCall(Double.valueOf(df.format(distanceOfVehicleFromCall)));
    distances.setPresentableDistance(presentationService.getPresentableDistance(distances));

    wrapper.setDistances(distances);
    distancesExtensions.setAny(wrapper);
    monitoredCallStructure.setExtensions(distancesExtensions);

    return monitoredCallStructure;
}