Example usage for java.lang Double toString

List of usage examples for java.lang Double toString

Introduction

In this page you can find the example usage for java.lang Double toString.

Prototype

public static String toString(double d) 

Source Link

Document

Returns a string representation of the double argument.

Usage

From source file:Main.java

public static void main(String[] args) {

    System.out.println(Double.toString(1.2));

}

From source file:Main.java

public static void main(String[] args) throws Exception {

    String str = Double.toString(23);
}

From source file:Main.java

public static void main(String[] args) {
    double d = 8.48;
    String s = Double.toString(d);
}

From source file:BigDecimalInvoiceApp.java

public static void main(String[] args) {
    double subtotal = 123.123;

    double discountPercent = 0.2;
    BigDecimal decimalSubtotal = new BigDecimal(Double.toString(subtotal));
    decimalSubtotal = decimalSubtotal.setScale(2, RoundingMode.HALF_UP);
    BigDecimal decimalDiscountPercent = new BigDecimal(Double.toString(discountPercent));

    BigDecimal discountAmount = decimalSubtotal.multiply(decimalDiscountPercent);
    discountAmount = discountAmount.setScale(2, RoundingMode.HALF_UP);

    BigDecimal totalBeforeTax = decimalSubtotal.subtract(discountAmount);
    BigDecimal salesTaxPercent = new BigDecimal(".05");
    BigDecimal salesTax = salesTaxPercent.multiply(totalBeforeTax);
    salesTax = salesTax.setScale(2, RoundingMode.HALF_UP);
    BigDecimal total = totalBeforeTax.add(salesTax);

    NumberFormat currency = NumberFormat.getCurrencyInstance();
    NumberFormat percent = NumberFormat.getPercentInstance();

    String message = "Subtotal:         " + currency.format(decimalSubtotal) + "\n" + "Discount percent: "
            + percent.format(decimalDiscountPercent) + "\n" + "Discount amount:  "
            + currency.format(discountAmount) + "\n" + "Total before tax: " + currency.format(totalBeforeTax)
            + "\n" + "Sales tax:        " + currency.format(salesTax) + "\n" + "Invoice total:    "
            + currency.format(total) + "\n";

    System.out.println(message);//from w w  w  .  j a v a2s.  c  o  m

}

From source file:ToStringDemo.java

public static void main(String[] args) {
    double d = 858.48;
    String s = Double.toString(d);

    int dot = s.indexOf('.');

    System.out.println(dot + " digits before decimal point.");
    System.out.println((s.length() - dot - 1) + " digits after decimal point.");
}

From source file:io.druid.query.aggregation.datasketches.quantiles.GenerateTestData.java

public static void main(String[] args) throws Exception {
    Path buildPath = FileSystems.getDefault().getPath("doubles_build_data.tsv");
    Path sketchPath = FileSystems.getDefault().getPath("doubles_sketch_data.tsv");
    BufferedWriter buildData = Files.newBufferedWriter(buildPath, StandardCharsets.UTF_8);
    BufferedWriter sketchData = Files.newBufferedWriter(sketchPath, StandardCharsets.UTF_8);
    Random rand = new Random();
    int sequenceNumber = 0;
    for (int i = 0; i < 20; i++) {
        int product = rand.nextInt(10);
        UpdateDoublesSketch sketch = UpdateDoublesSketch.builder().build();
        for (int j = 0; j < 20; j++) {
            double value = rand.nextDouble();
            buildData.write("2016010101");
            buildData.write('\t');
            buildData.write(Integer.toString(sequenceNumber)); // dimension with unique numbers for ingesting raw data
            buildData.write('\t');
            buildData.write(Integer.toString(product)); // product dimension
            buildData.write('\t');
            buildData.write(Double.toString(value));
            buildData.newLine();/* w  w  w. ja va2s .  co m*/
            sketch.update(value);
            sequenceNumber++;
        }
        sketchData.write("2016010101");
        sketchData.write('\t');
        sketchData.write(Integer.toString(product)); // product dimension
        sketchData.write('\t');
        sketchData.write(Base64.encodeBase64String(sketch.toByteArray(true)));
        sketchData.newLine();
    }
    buildData.close();
    sketchData.close();
}

From source file:org.jfree.chart.demo.Display.java

/**
 * Launch the application./*from w ww  .  j  a va2 s .  c  o m*/
 */
public static void main(String[] args) throws IOException {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Display window = new Display();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ////////////
        }
    });

    try {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s;
        File dataFile = new File("data.txt");
        FileWriter fw = new FileWriter(dataFile);
        BufferedWriter bw = new BufferedWriter(fw);
        DataParser datIn = new DataParser(effectiveX, effectiveY);

        //while(!enabled){}//spin until enabled

        while ((s = in.readLine()) != null && s.length() != 0 && enabled) {
            // System.out.println(s);
            if (datIn.parseString(s)) {
                bw.write(s);
                bw.write('\n');
                bw.flush();
                panel_1.plotCoords(datIn.getX(), datIn.getFlippedY());
                TimeElapsed.setText(Double.toString(datIn.getTime()));
            }
        }

        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.datastax.brisk.demo.pricer.Pricer.java

public static void main(String[] arguments) throws Exception {
    long latency, oldLatency;
    int epoch, total, oldTotal, keyCount, oldKeyCount;

    try {//w w w .j a v a  2 s.  c o  m
        session = new Session(arguments);
    } catch (IllegalArgumentException e) {
        printHelpMessage();
        return;
    }

    session.createKeySpaces();

    int threadCount = session.getThreads();
    Thread[] consumers = new Thread[threadCount];
    PrintStream out = session.getOutputStream();

    out.println("total,interval_op_rate,interval_key_rate,avg_latency,elapsed_time");

    int itemsPerThread = session.getKeysPerThread();
    int modulo = session.getNumKeys() % threadCount;

    // creating required type of the threads for the test
    for (int i = 0; i < threadCount; i++) {
        if (i == threadCount - 1)
            itemsPerThread += modulo; // last one is going to handle N + modulo items

        consumers[i] = new Consumer(itemsPerThread);
    }

    new Producer().start();

    // starting worker threads
    for (int i = 0; i < threadCount; i++) {
        consumers[i].start();
    }

    // initialization of the values
    boolean terminate = false;
    latency = 0;
    epoch = total = keyCount = 0;

    int interval = session.getProgressInterval();
    int epochIntervals = session.getProgressInterval() * 10;
    long testStartTime = System.currentTimeMillis();

    while (!terminate) {
        Thread.sleep(100);

        int alive = 0;
        for (Thread thread : consumers)
            if (thread.isAlive())
                alive++;

        if (alive == 0)
            terminate = true;

        epoch++;

        if (terminate || epoch > epochIntervals) {
            epoch = 0;

            oldTotal = total;
            oldLatency = latency;
            oldKeyCount = keyCount;

            total = session.operations.get();
            keyCount = session.keys.get();
            latency = session.latency.get();

            int opDelta = total - oldTotal;
            int keyDelta = keyCount - oldKeyCount;
            double latencyDelta = latency - oldLatency;

            long currentTimeInSeconds = (System.currentTimeMillis() - testStartTime) / 1000;
            String formattedDelta = (opDelta > 0) ? Double.toString(latencyDelta / (opDelta * 1000)) : "NaN";

            out.println(String.format("%d,%d,%d,%s,%d", total, opDelta / interval, keyDelta / interval,
                    formattedDelta, currentTimeInSeconds));
        }
    }
}

From source file:CTmousetrack.java

public static void main(String[] args) {

    String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder
    String srcName = "CTmousetrack"; // name of the output CT source
    long blockPts = 10; // points per block flush
    long sampInterval = 10; // time between sampling updates, msec
    double trimTime = 0.0; // amount of data to keep (trim time), sec
    boolean debug = false; // turn on debug?

    // Specify the CT output connection
    CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data
    String serverHost = ""; // Server (FTP or HTTP/S) host:port
    String serverUser = ""; // Server (FTP or HTTPS) username
    String serverPassword = ""; // Server (FTP or HTTPS) password

    // For UDP output mode
    DatagramSocket udpServerSocket = null;
    InetAddress udpServerAddress = null;
    String udpHost = "";
    int udpPort = -1;

    // Concatenate all of the CTWriteMode types
    String possibleWriteModes = "";
    for (CTWriteMode wm : CTWriteMode.values()) {
        possibleWriteModes = possibleWriteModes + ", " + wm.name();
    }/*from   ww w.  j  av  a  2 s .  c om*/
    // Remove ", " from start of string
    possibleWriteModes = possibleWriteModes.substring(2);

    //
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption(Option.builder("o").argName("base output dir").hasArg().desc(
            "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \""
                    + outLoc + "\".")
            .build());
    options.addOption(Option.builder("s").argName("source name").hasArg()
            .desc("Name of source to write data to; default = \"" + srcName + "\".").build());
    options.addOption(Option.builder("b").argName("points per block").hasArg()
            .desc("Number of points per block; UDP output mode will use 1 point/block; default = "
                    + Long.toString(blockPts) + ".")
            .build());
    options.addOption(Option.builder("dt").argName("samp interval msec").hasArg()
            .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build());
    options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc(
            "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(
            Option.builder("w").argName("write mode").hasArg()
                    .desc("Type of write connection; one of " + possibleWriteModes
                            + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".")
                    .build());
    options.addOption(Option.builder("host").argName("host[:port]").hasArg()
            .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build());
    options.addOption(Option.builder("u").argName("username,password").hasArg()
            .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build());
    options.addOption("x", "debug", false, "Enable CloudTurbine debug output.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("CTmousetrack", "", options,
                "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port.");
        return;
    }

    outLoc = line.getOptionValue("o", outLoc);
    if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) {
        outLoc = outLoc + File.separator;
    }
    // Make sure the base output folder location ends in "CTdata"
    if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) {
        outLoc = outLoc + "CTdata" + File.separator;
    }

    srcName = line.getOptionValue("s", srcName);

    blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts)));

    sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval)));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    // Type of output connection
    String writeModeStr = line.getOptionValue("w", writeMode.name());
    boolean bMatch = false;
    for (CTWriteMode wm : CTWriteMode.values()) {
        if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) {
            writeMode = wm;
            bMatch = true;
        }
    }
    if (!bMatch) {
        System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of "
                + possibleWriteModes);
        System.exit(0);
    }
    if (writeMode != CTWriteMode.LOCAL) {
        // User must have specified the host
        // If FTP or HTTPS, they may also specify username/password
        serverHost = line.getOptionValue("host", serverHost);
        if (serverHost.isEmpty()) {
            System.err.println(
                    "When using write mode \"" + writeModeStr + "\", you must specify the server host.");
            System.exit(0);
        }
        if (writeMode == CTWriteMode.UDP) {
            // Force blockPts to be 1
            blockPts = 1;
            // User must have specified both host and port
            int colonIdx = serverHost.indexOf(':');
            if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) {
                System.err.println(
                        "For UDP output mode, both the host and port (<host>:<port>)) must be specified.");
                System.exit(0);
            }
            udpHost = serverHost.substring(0, colonIdx);
            String udpPortStr = serverHost.substring(colonIdx + 1);
            try {
                udpPort = Integer.parseInt(udpPortStr);
            } catch (NumberFormatException nfe) {
                System.err.println("The UDP port must be a positive integer.");
                System.exit(0);
            }
        }
        if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) {
            String userpassStr = line.getOptionValue("u", "");
            if (!userpassStr.isEmpty()) {
                // This string should be comma-delimited username and password
                String[] userpassCSV = userpassStr.split(",");
                if (userpassCSV.length != 2) {
                    System.err.println("When specifying a username and password for write mode \""
                            + writeModeStr + "\", separate the username and password by a comma.");
                    System.exit(0);
                }
                serverUser = userpassCSV[0];
                serverPassword = userpassCSV[1];
            }
        }
    }

    debug = line.hasOption("debug");

    System.err.println("CTmousetrack parameters:");
    System.err.println("\toutput mode = " + writeMode.name());
    if (writeMode == CTWriteMode.UDP) {
        System.err.println("\twrite to " + udpHost + ":" + udpPort);
    } else {
        System.err.println("\tsource = " + srcName);
        System.err.println("\ttrim time = " + trimTime + " sec");
    }
    System.err.println("\tpoints per block = " + blockPts);
    System.err.println("\tsample interval = " + sampInterval + " msec");

    try {
        //
        // Setup CTwriter or UDP output
        //
        CTwriter ctw = null;
        CTinfo.setDebug(debug);
        if (writeMode == CTWriteMode.LOCAL) {
            ctw = new CTwriter(outLoc + srcName, trimTime);
            System.err.println("\tdata will be written to local folder \"" + outLoc + "\"");
        } else if (writeMode == CTWriteMode.FTP) {
            CTftp ctftp = new CTftp(srcName);
            try {
                ctftp.login(serverHost, serverUser, serverPassword);
            } catch (Exception e) {
                throw new IOException(
                        new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage()));
            }
            ctw = ctftp; // upcast to CTWriter
            System.err.println("\tdata will be written to FTP server at " + serverHost);
        } else if (writeMode == CTWriteMode.HTTP) {
            // Don't send username/pw in HTTP mode since they will be unencrypted
            CThttp cthttp = new CThttp(srcName, "http://" + serverHost);
            ctw = cthttp; // upcast to CTWriter
            System.err.println("\tdata will be written to HTTP server at " + serverHost);
        } else if (writeMode == CTWriteMode.HTTPS) {
            CThttp cthttp = new CThttp(srcName, "https://" + serverHost);
            // Username/pw are optional for HTTPS mode; only use them if username is not empty
            if (!serverUser.isEmpty()) {
                try {
                    cthttp.login(serverUser, serverPassword);
                } catch (Exception e) {
                    throw new IOException(new String(
                            "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage()));
                }
            }
            ctw = cthttp; // upcast to CTWriter
            System.err.println("\tdata will be written to HTTPS server at " + serverHost);
        } else if (writeMode == CTWriteMode.UDP) {
            try {
                udpServerSocket = new DatagramSocket();
            } catch (SocketException se) {
                System.err.println("Error creating socket for UDP:\n" + se);
                System.exit(0);
            }
            try {
                udpServerAddress = InetAddress.getByName(udpHost);
            } catch (UnknownHostException uhe) {
                System.err.println("Error getting UDP server host address:\n" + uhe);
                System.exit(0);
            }
        }
        if (writeMode != CTWriteMode.UDP) {
            ctw.setBlockMode(blockPts > 1, blockPts > 1);
            ctw.autoFlush(0); // no autoflush
            ctw.autoSegment(1000);
        }

        // screen dims
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        double width = screenSize.getWidth();
        double height = screenSize.getHeight();

        // use Map for consolidated putData
        Map<String, Object> cmap = new LinkedHashMap<String, Object>();

        // loop and write some output
        for (int i = 0; i < 1000000; i++) { // go until killed
            long currentTime = System.currentTimeMillis();
            Point mousePos = MouseInfo.getPointerInfo().getLocation();
            float x_pt = (float) (mousePos.getX() / width); // normalize
            float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0)
            if (writeMode != CTWriteMode.UDP) {
                // CT output mode
                ctw.setTime(currentTime);
                cmap.clear();
                cmap.put("x", x_pt);
                cmap.put("y", y_pt);
                ctw.putData(cmap);
                if (((i + 1) % blockPts) == 0) {
                    ctw.flush();
                    System.err.print(".");
                }
            } else {
                // UDP output mode
                // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time
                // Write the following data (21 bytes total):
                //     header = "MOUSE", 5 bytes
                //     current time, long, 8 bytes
                //     2 floats (x,y) 4 bytes each, 8 bytes
                int len = 21;
                ByteBuffer bb = ByteBuffer.allocate(len);
                String headerStr = "MOUSE";
                bb.put(headerStr.getBytes("UTF-8"));
                bb.putLong(currentTime);
                bb.putFloat(x_pt);
                bb.putFloat(y_pt);
                // Might be able to use the following, but not sure:
                //     byte[] sendData = bb.array();
                byte[] sendData = new byte[len];
                bb.position(0);
                bb.get(sendData, 0, len);
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress,
                        udpPort);
                try {
                    udpServerSocket.send(sendPacket);
                } catch (IOException e) {
                    System.err.println("Test server caught exception trying to send data to UDP client:\n" + e);
                }
                System.err.print(".");
            }
            try {
                Thread.sleep(sampInterval);
            } catch (Exception e) {
            }
            ;
        }
        if (writeMode != CTWriteMode.UDP) {
            ctw.flush(); // wrap up
        }
    } catch (Exception e) {
        System.err.println("CTmousetrack exception: " + e);
        e.printStackTrace();
    }
}

From source file:geocodingissues.Main.java

/**
 * @param args the command line arguments
 *//*from  w  w w.  j  ava 2 s. co  m*/
public static void main(String[] args) throws JSONException {
    Main x = new Main();
    ResultSet rs = null;

    x.establishConnection();
    //x.addColumns(); //already did this

    rs = x.getLatLong();

    int id;
    double latitude;
    double longitude;
    String req;

    String street_no;
    String street;
    String neighborhood;
    String locality;
    String PC;

    JSONObject jObject;
    JSONArray resultArray;
    JSONArray compArray;

    try {
        while (rs.next()) {
            id = rs.getInt("id");
            latitude = rs.getDouble("latitude");
            longitude = rs.getDouble("longitude");

            //System.out.println("id: " + id);

            req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + Double.toString(latitude) + ","
                    + Double.toString(longitude)
                    + "&result_type=street_address|neighborhood|locality|postal_code&key=" + key;

            try {
                URL url = new URL(req + "&sensor=false");
                URLConnection conn = url.openConnection();
                ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
                IOUtils.copy(conn.getInputStream(), output);
                output.close();
                req = output.toString();
            } catch (Exception e) {
                System.out.println("Geocoding Error");
            }
            if (req.contains("OVER_QUERY_LIMIT")) {
                System.out.println("Over Daily Query Limit");
                System.exit(0);
            }
            if (!req.contains("ZERO_RESULTS")) {
                //System.out.println("req: ");
                //System.out.println(req);
                jObject = new JSONObject(req);
                resultArray = jObject.getJSONArray("results");

                // Retrieve information on street address and insert into table
                compArray0 = resultArray.getJSONObject(0).getJSONArray("address_components");
                street_no = compArray0.getJSONObject(0).getString("long_name");
                street = compArray0.getJSONObject(1).getString("long_name");
                x.insertValues(id, street_no, street);

                // Retrieve information on neighborhood and insert into table
                compArray1 = resultArray.getJSONObject(1).getJSONArray("address_components");
                neighborhood = compArray1.getJSONObject(0).getString("long_name");
                x.insertNbhd(id, neighborhood);

                // Retrieve information on locality and insert into table
                compArray2 = resultArray.getJSONObject(2).getJSONArray("address_components");
                locality = compArray2.getJSONObject(0).getString("long_name");
                x.insertLocality(id, locality);

                // Retrieve information on postal code and insert into table
                compArray3 = resultArray.getJSONObject(3).getJSONArray("address_components");
                PC = compArray3.getJSONObject(0).getString("long_name");
                x.insertPC(id, PC);
            }
        }
    } catch (Exception e) {
        System.out.println("Problem when updating the database.");
    }
    x.closeConnection();
}