Example usage for java.text DecimalFormatSymbols DecimalFormatSymbols

List of usage examples for java.text DecimalFormatSymbols DecimalFormatSymbols

Introduction

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

Prototype

public DecimalFormatSymbols(Locale locale) 

Source Link

Document

Create a DecimalFormatSymbols object for the given locale.

Usage

From source file:nl.strohalm.cyclos.entities.settings.LocalSettings.java

public DecimalFormatSymbols getDecimalSymbols() {
    if (decimalSymbols == null) {
        decimalSymbols = new DecimalFormatSymbols(numberLocale.getLocale());
    }/*from   w  w w.j a v  a2  s. c  o  m*/
    return decimalSymbols;
}

From source file:org.freeplane.features.format.FormatController.java

/** @param pattern either a string (see {@link DecimalFormat}) or null for a default formatter. */
public DecimalFormat getDecimalFormat(final String pattern) {
    DecimalFormat format = numberFormatCache.get(pattern);
    if (format == null) {
        format = (DecimalFormat) ((pattern == null) ? getDefaultNumberFormat()
                : new DecimalFormat(pattern,
                        new DecimalFormatSymbols(FormatUtils.getFormatLocaleFromResources())));
        numberFormatCache.put(pattern, format);
    }//from  ww w  .ja va2s .co  m
    return format;
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public get_geocaches_ret get_geocaches_v2(Coordinate[] location, int count_p, int max_p, int rec_depth,
        Handler h, int zoom_level) {
    this.main_aagtl.set_bar_slow(h, "get geocaches", "downloading ...", count_p, max_p, true);

    if (zoom_level > 16) {
        zoom_level = 16;//from ww w .  j a v  a 2  s.  com
    } else if (zoom_level < 6) {
        zoom_level = 6;
    }

    get_geocaches_ret rr2 = new get_geocaches_ret();
    Coordinate c1 = location[0];
    Coordinate c2 = location[1];

    String zoomlevel_ = "" + zoom_level;

    // use "." as comma seperator!!
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    DecimalFormat format_lat_lon = new DecimalFormat("#.#####", otherSymbols);
    // use "." as comma seperator!!

    // http://www.geocaching.com/map/default.aspx?ll=48.22607,16.36997
    // GET http://www.geocaching.com/map/default.aspx?ll=48.22607,16.36997 HTTP/1.1
    String lat_str = format_lat_lon.format((c1.lat + c2.lat) / 2);
    String lon_str = format_lat_lon.format((c1.lon + c2.lon) / 2);
    //String url = "http://www.geocaching.com/map/?ll=" + lat_str + "," + lon_str + "&z=" + zoomlevel_;
    String url = "http://www.geocaching.com/map/default.aspx?ll=" + lat_str + "," + lon_str;
    System.out.println("url=" + url);

    List<NameValuePair> values_list = new ArrayList<NameValuePair>();
    //*values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
    //*values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
    // values_list.add(new BasicNameValuePair("Referer","http://www.geocaching.com/map/default.aspx"));
    //ByteArrayOutputStream bs = new ByteArrayOutputStream();
    String the_page = get_reader_stream(url, values_list, null, true);
    //String the_page = getUrlData(url);

    //System.out.println(the_page);

    // get values --------------------------
    // get values --------------------------
    // Groundspeak.Map.UserSession('xxxx', 
    Pattern p = Pattern.compile("Groundspeak\\.Map\\.UserSession.'([^']*)'");
    Matcher m = p.matcher(the_page);
    Boolean has_found = true;
    String kk_ = "";
    try {
        has_found = m.find();
        kk_ = m.group(1);
    } catch (Exception e3) {
        e3.printStackTrace();
    }
    System.out.println("kk=" + kk_);

    // sessionToken:'
    p = Pattern.compile("sessionToken:'([^']*)'");
    m = p.matcher(the_page);
    has_found = m.find();
    String sess_token_ = m.group(1);

    System.out.println("sess_token=" + sess_token_);
    // get values --------------------------
    // get values --------------------------

    java.util.Date date = new java.util.Date();
    System.out.println("ts=" + date.getTime());

    String timestamp_ = "" + date.getTime(); // ..seconds..

    // lat, lon -> tile
    Coordinate coord = new Coordinate((c1.lat + c2.lat) / 2, (c1.lon + c2.lon) / 2);
    double[] tile = main_aagtl.rose.deg2num_give_zoom(coord, zoom_level);
    String xtile_num = "" + ((int) tile[0]);
    String ytile_num = "" + ((int) tile[1]);
    // lat, lon -> tile

    // X-Requested-With: XMLHttpRequest
    //Referer: http://www.geocaching.com/map/default.aspx?ll=48.22607,16.36997
    values_list = new ArrayList<NameValuePair>();
    //values_list.add(new BasicNameValuePair("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"));
    //values_list.add(new BasicNameValuePair("Pragma", "no-cache"));
    //values_list.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
    //values_list.add(new BasicNameValuePair("Referer", "http://www.geocaching.com/map/default.aspx?ll=" + lat_str + "," + lon_str));

    String url2 = "http://www.geocaching.com/map/map.info?x=" + xtile_num + "&y=" + ytile_num + "&z="
            + zoomlevel_ + "&k=" + kk_ + "&st=" + sess_token_ + "&ep=1&_=" + timestamp_;

    System.out.println("url2=" + url2);

    the_page = get_reader_stream(url2, values_list, null, true);
    // the_page = getUrlData(url2);
    try {
        System.out.println(the_page);
    } catch (Exception e3) {

    }

    // we need to add one, in any case!
    count_p = count_p + 1;
    get_geocaches_ret r = new get_geocaches_ret();
    r.count_p = count_p;
    r.points = null;
    return r;
}

From source file:fr.cs.examples.bodies.Phasing.java

/** Print ground track grid point
 * @param out output stream//  w w  w  .  j  av  a 2s .c o m
 * @param latitude point latitude
 * @param ascending indicator for latitude crossing direction
 * @param orbit phased orbit
 * @param propagator propagator for orbit
 * @param nbOrbits number of orbits in the cycle
 * @exception OrekitException if orbit cannot be propagated
 */
private void printGridPoints(final PrintStream out, final double latitude, final boolean ascending,
        final Orbit orbit, final Propagator propagator, int nbOrbits) throws OrekitException {

    propagator.resetInitialState(new SpacecraftState(orbit));
    AbsoluteDate start = orbit.getDate();

    // find the first latitude crossing
    double period = orbit.getKeplerianPeriod();
    double stepSize = period / 100;
    SpacecraftState crossing = findFirstCrossing(latitude, ascending, start, start.shiftedBy(2 * period),
            stepSize, propagator);

    // find all other latitude crossings from regular schedule
    DecimalFormat fTime = new DecimalFormat("0000000.000", new DecimalFormatSymbols(Locale.US));
    DecimalFormat fAngle = new DecimalFormat("000.00000", new DecimalFormatSymbols(Locale.US));
    while (nbOrbits-- > 0) {

        GeodeticPoint gp = earth.transform(crossing.getPVCoordinates().getPosition(), crossing.getFrame(),
                crossing.getDate());
        out.println(fTime.format(crossing.getDate().durationFrom(start)) + " "
                + fAngle.format(FastMath.toDegrees(gp.getLatitude())) + " "
                + fAngle.format(FastMath.toDegrees(gp.getLongitude())) + " " + ascending);

        final AbsoluteDate previousDate = crossing.getDate();
        crossing = findLatitudeCrossing(latitude, previousDate.shiftedBy(period),
                previousDate.shiftedBy(2 * period), stepSize, period / 8, propagator);
        period = crossing.getDate().durationFrom(previousDate);

    }

}

From source file:com.tonbeller.jpivot.chart.ChartComponent.java

/**
 * Get cell value as a Number. Parses the cell value string
 * using the locale set in this.locale./*  w w  w .  j  a  v  a 2  s  . c o  m*/
 * @param cell
 * @return value as Number (can be null)
 */
private Number getNumberValue(Cell cell) {
    //**** HACK AR 2004.01.10
    //String value = cell.getFormattedValue();
    Object value = cell.getValue();

    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(dfs);
    Number number = null;
    try {
        number = (Number) value;
        //number = formatter.parse(value, new ParsePosition(0));
    } catch (Exception e) {
        number = null;
    }
    return number;
}

From source file:Matrix.java

/**
 * Print the matrix to the output stream. Line the elements up in columns
 * with a Fortran-like 'Fw.d' style format.
 * /*from   w ww.j  a  v  a2  s. c om*/
 * @param output
 *            Output stream.
 * @param w
 *            Column width.
 * @param d
 *            Number of digits after the decimal.
 */

public void print(PrintWriter output, int w, int d) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(d);
    format.setMinimumFractionDigits(d);
    format.setGroupingUsed(false);
    print(output, format, w + 2);
}

From source file:org.rythmengine.utils.S.java

/**
 * Format the number with specified template, pattern, language and locale
 * @param number/*from   ww w  .j a  va2s  . c  om*/
 * @param pattern
 * @param locale
 * @return the formatted String
 * @see DecimalFormatSymbols
 */
public static String format(ITemplate template, Number number, String pattern, Locale locale) {
    if (null == number)
        number = 0;
    if (null == locale) {
        locale = I18N.locale(template);
    }

    NumberFormat nf;
    if (null == pattern)
        nf = NumberFormat.getNumberInstance(locale);
    else {
        DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
        nf = new DecimalFormat(pattern, symbols);
    }

    return nf.format(number);
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.RMRest.java

@Override
@GET/*from   w w  w .  ja v  a  2s  .co  m*/
@GZIP
@Path("stathistory")
@Produces("application/json")
public String getStatHistory(@HeaderParam("sessionid") String sessionId, @QueryParam("range") String range)
        throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException,
        MalformedObjectNameException, NullPointerException, InterruptedException, NotConnectedException {

    RMProxyUserInterface rm = checkAccess(sessionId);

    // if range String is too large, shorten it
    // to make it recognizable by StatHistoryCaching
    if (range.length() > dataSources.length) {
        range = range.substring(0, dataSources.length);
    }
    // complete range if too short
    while (range.length() < dataSources.length) {
        range += 'a';
    }

    StatHistoryCacheEntry cache = StatHistoryCaching.getInstance().getEntry(range);
    // found unexpired cache entry matching the parameters: return it immediately
    if (cache != null) {
        return cache.getValue();
    }

    long l1 = System.currentTimeMillis();

    ObjectName on = new ObjectName(RMJMXBeans.RUNTIMEDATA_MBEAN_NAME);
    AttributeList attrs = rm.getMBeanAttributes(on, new String[] { "StatisticHistory" });
    Attribute attr = (Attribute) attrs.get(0);
    // content of the RRD4J database backing file
    byte[] rrd4j = (byte[]) attr.getValue();

    File rrd4jDb = File.createTempFile("database", "rr4dj");
    rrd4jDb.deleteOnExit();

    try (OutputStream out = new FileOutputStream(rrd4jDb)) {
        out.write(rrd4j);
    }

    // create RRD4J DB, should be identical to the one held by the RM
    RrdDb db = new RrdDb(rrd4jDb.getAbsolutePath(), true);

    long timeEnd = db.getLastUpdateTime();
    // force float separator for JSON parsing
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    // formatting will greatly reduce response size
    DecimalFormat formatter = new DecimalFormat("###.###", otherSymbols);

    // construct the JSON response directly in a String
    StringBuilder result = new StringBuilder();
    result.append("{");

    for (int i = 0; i < dataSources.length; i++) {
        String dataSource = dataSources[i];
        char zone = range.charAt(i);
        long timeStart;

        switch (zone) {
        default:
        case 'a': // 1 minute
            timeStart = timeEnd - 60;
            break;
        case 'm': // 10 minute
            timeStart = timeEnd - 60 * 10;
            break;
        case 'h': // 1 hours
            timeStart = timeEnd - 60 * 60;
            break;
        case 'H': // 8 hours
            timeStart = timeEnd - 60 * 60 * 8;
            break;
        case 'd': // 1 day
            timeStart = timeEnd - 60 * 60 * 24;
            break;
        case 'w': // 1 week
            timeStart = timeEnd - 60 * 60 * 24 * 7;
            break;
        case 'M': // 1 month
            timeStart = timeEnd - 60 * 60 * 24 * 28;
            break;
        case 'y': // 1 year
            timeStart = timeEnd - 60 * 60 * 24 * 365;
            break;
        }

        FetchRequest req = db.createFetchRequest(ConsolFun.AVERAGE, timeStart, timeEnd);
        req.setFilter(dataSource);
        FetchData fetchData = req.fetchData();
        result.append("\"").append(dataSource).append("\":[");

        double[] values = fetchData.getValues(dataSource);
        for (int j = 0; j < values.length; j++) {
            if (Double.compare(Double.NaN, values[j]) == 0) {
                result.append("null");
            } else {
                result.append(formatter.format(values[j]));
            }
            if (j < values.length - 1)
                result.append(',');
        }
        result.append(']');
        if (i < dataSources.length - 1)
            result.append(',');
    }
    result.append("}");

    db.close();
    rrd4jDb.delete();

    String ret = result.toString();

    StatHistoryCaching.getInstance().addEntry(range, l1, ret);

    return ret;
}

From source file:nl.umcg.westrah.binarymetaanalyzer.BinaryMetaAnalysis.java

private void writeBuffer(String outdir, int permutation) throws IOException {

    // sort the finalbuffer for a last time
    if (locationToStoreResult != 0) {
        Arrays.parallelSort(finalEQTLs, 0, locationToStoreResult);
    }//  w  w  w .ja  va  2  s.  co m

    String outfilename = outdir + "eQTLs.txt.gz";
    FileFormat outformat = FileFormat.LARGE;
    if (permutation > 0) {
        outfilename = outdir + "PermutedEQTLsPermutationRound" + permutation + ".txt.gz";
        if (!fullpermutationoutput) {
            outformat = FileFormat.REDUCED;
        }
    }

    String tab = "\t";
    String newline = "\n";

    TextFile output = new TextFile(outfilename, TextFile.W, 10 * 1048576);

    String header = "PValue\t" + "SNPName\t" + "SNPChr\t" + "SNPChrPos\t" + "ProbeName\t" + "ProbeChr\t"
            + "ProbeCenterChrPos\t" + "CisTrans\t" + "SNPType\t" + "AlleleAssessed\t" + "OverallZScore\t"
            + "DatasetsWhereSNPProbePairIsAvailableAndPassesQC\t" + "DatasetsZScores\t" + "DatasetsNrSamples\t"
            + "IncludedDatasetsMeanProbeExpression\t" + "IncludedDatasetsProbeExpressionVariance\t"
            + "HGNCName\t" + "IncludedDatasetsCorrelationCoefficient\t" + "Meta-Beta (SE)\t" + "Beta (SE)\t"
            + "FoldChange";
    if (outformat.equals(FileFormat.REDUCED)) {
        header = "PValue\tSNP\tProbe\tGene\tAlleles\tAlleleAssessed\tZScore";
    }
    output.writeln(header);
    // PValue   SNPName   SNPChr   SNPChrPos   ProbeName   ProbeChr   ProbeCenterChrPos   CisTrans   SNPType   AlleleAssessed   OverallZScore   DatasetsWhereSNPProbePairIsAvailableAndPassesQC   DatasetsZScores   DatasetsNrSamples   IncludedDatasetsMeanProbeExpression   IncludedDatasetsProbeExpressionVariance   HGNCName   IncludedDatasetsCorrelationCoefficient   Meta-Beta (SE)   Beta (SE)   FoldChange   FDR

    DecimalFormat dformat = new DecimalFormat("###.####", new DecimalFormatSymbols(Locale.US));
    DecimalFormat pformat = new DecimalFormat("###.########", new DecimalFormatSymbols(Locale.US));
    DecimalFormat smallpFormat = new DecimalFormat("0.####E0", new DecimalFormatSymbols(Locale.US));

    int ctr = 0;
    for (int i = 0; i < settings.getFinalEQTLBufferMaxLength(); i++) {
        if (finalEQTLs[i] != null) {
            ctr++;
        }
    }
    int totalctr = 0;
    for (int i = 0; i < finalEQTLs.length; i++) {
        if (finalEQTLs[i] != null) {
            totalctr++;
        }
    }
    System.out.println("There are " + ctr + " results in the buffer to write. " + totalctr
            + " QTLs are in memory at the moment.");
    ProgressBar pb = new ProgressBar(ctr, "Writing: " + outfilename);

    String cistr = "Cis";
    String transtr = "Trans";
    String greyz = "Greyzone";

    for (int i = 0; i < settings.getFinalEQTLBufferMaxLength(); i++) {
        QTL q = finalEQTLs[i];
        if (q != null) {
            //            StringBuilder sb = new StringBuilder(4096);
            if (outformat.equals(FileFormat.LARGE)) {
                if (q.getPvalue() < 1E-4) {
                    output.append(smallpFormat.format(q.getPvalue()));
                } else {
                    output.append(pformat.format(q.getPvalue()));
                }
                output.append(tab);
                int snpId = q.getSNPId();
                output.append(snpList[snpId]);
                output.append(tab);
                output.append(snpChr[snpId]);
                output.append(tab);
                output.append("" + snpPositions[snpId]);
                output.append(tab);
                MetaQTL4MetaTrait t = q.getMetaTrait();
                output.append(t.getMetaTraitName());
                output.append(tab);
                output.append(t.getChr());
                output.append(tab);
                output.append("" + t.getChrMidpoint());
                output.append(tab);
                int dist = Math.abs(t.getChrMidpoint() - snpPositions[snpId]);
                boolean sameChr = t.getChr().equals(snpChr[snpId]);
                if (sameChr && dist < settings.getCisdistance()) {
                    output.append(cistr);
                } else if (sameChr && dist < settings.getTransdistance()) {
                    output.append(greyz);
                } else {
                    output.append(transtr);
                }

                output.append(tab);
                output.append(q.getAlleles());
                output.append(tab);
                output.append(q.getAlleleAssessed());
                output.append(tab);
                output.append(dformat.format(q.getZscore()));

                float[] datasetZScores = q.getDatasetZScores();
                String[] dsBuilder = new String[datasets.length];
                String[] dsNBuilder = new String[datasets.length];
                String[] dsZBuilder = new String[datasets.length];

                for (int d = 0; d < datasetZScores.length; d++) {

                    if (!Float.isNaN(datasetZScores[d])) {
                        String str = dformat.format(datasetZScores[d]);

                        dsBuilder[d] = settings.getDatasetnames().get(d);
                        dsNBuilder[d] = "" + q.getDatasetSampleSizes()[d];
                        dsZBuilder[d] = str;
                    } else {
                        dsBuilder[d] = "-";
                        dsNBuilder[d] = "-";
                        dsZBuilder[d] = "-";
                    }
                }

                output.append(tab);
                output.append(Strings.concat(dsBuilder, Strings.semicolon));

                output.append(tab);
                output.append(Strings.concat(dsZBuilder, Strings.semicolon));

                output.append(tab);
                output.append(Strings.concat(dsNBuilder, Strings.semicolon));
                output.append("\t-\t-\t");

                output.append(t.getAnnotation());
                output.append("\t-\t-\t-\t-");
                output.append(newline);

            } else {
                //               header = "PValue\tSNP\tProbe\tGene\tAlleles\tAlleleAssessed\tZScore";

                int snpId = q.getSNPId();
                MetaQTL4MetaTrait t = q.getMetaTrait();

                if (q.getPvalue() < 1E-4) {
                    output.append(smallpFormat.format(q.getPvalue()));
                } else {
                    output.append(pformat.format(q.getPvalue()));
                }
                output.append(tab);
                output.append(snpList[snpId]);
                output.append(tab);
                output.append(t.getMetaTraitName());
                output.append(tab);
                output.append(t.getAnnotation());
                output.append(tab);
                output.append(q.getAlleles());
                output.append(tab);
                output.append(q.getAlleleAssessed());
                output.append(tab);
                output.append(dformat.format(q.getZscore()));
                output.append(newline);
            }

            pb.iterate();
        }
        finalEQTLs[i] = null; // trash it immediately
    }

    pb.close();
    output.close();
    finalEQTLs = null; // ditch the whole resultset

    if (usetmp) {

        String filename = "eQTLs.txt.gz";
        if (permutation > 0) {
            filename = "PermutedEQTLsPermutationRound" + permutation + ".txt.gz";
        }
        File source = new File(tempDir + filename);
        File dest = new File(settings.getOutput() + filename);
        if (dest.exists()) {
            System.out.println("Destination file: " + dest.getAbsolutePath() + " exists already.. Deleting!");
            dest.delete();
        }
        System.out.println("Moving file: " + tempDir + filename + " --> " + settings.getOutput() + filename);
        FileUtils.moveFile(source, dest);

    }

    System.out.println("Done.");
}

From source file:com.marand.thinkmed.medications.business.impl.TherapyDisplayProvider.java

public String getFormattedDecimalValue(final String decimalValue, final Locale locale, final boolean bold) {
    if (decimalValue == null || locale == null) {
        return "";
    }/*from w  ww .j  a  v  a2  s  . co m*/
    final DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    final Character decimalSeparator = dfs.getDecimalSeparator();
    final String splitDelimiter = decimalSeparator.equals(new Character('.')) ? "\\." : ",";

    String formattedValue = decimalValue;
    final Pattern p = Pattern.compile("\\d+" + splitDelimiter + "\\d+"); // or ("[0-9]+" + splitDelimiter + "[0-9]+") ?
    final Matcher m = p.matcher(formattedValue);
    while (m.find()) {
        final String[] decimalNumbers = m.group().split(splitDelimiter);
        if (decimalNumbers.length == 2) {
            formattedValue = formattedValue.replaceAll(m.group(),
                    decimalNumbers[0] + splitDelimiter + createSpannedValue(decimalNumbers[1],
                            "TextDataSmallerDecimal" + (bold ? " bold" : ""), false));
        }
    }
    return formattedValue;
}