Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

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

Prototype

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:invoice.GetInvoice.java

/**
 * @param args the command line arguments
 *///from   w w w.  jav a2  s  .  c om
public static void main(String[] args) {

    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);
    nf.setRoundingMode(RoundingMode.HALF_UP);

    try {
        JSONObject arg_json = new JSONObject(args[0]);
    } catch (JSONException ex) {
        Logger.getLogger(GetInvoice.class.getName()).log(Level.SEVERE, null, ex);
    }
    HashMap<String, Object> hm = new HashMap<>();
    hm.put("duplicate", "");
    hm.put("distributor", "//oshan" + "\n" + "//kapuhempala" + "\n\nArea: " + "//galle");
    hm.put("customer", "//owner" + "\n" + "//Agro" + "\n" + "//Agro add" + "\n" + "//0771894851");
    hm.put("invNo", "GSLTS" + String.format("%04d", Integer.parseInt("//100")));
    hm.put("invDate", "2014-01-10");
    hm.put("invCode", "300");

    double invoiceTotal = 500000;
    if (5 > 0) {//ShopDiscount
        double discountprice = (invoiceTotal * 99) / 100;//getShopDiscount()
        hm.put("invoiceDiscount", nf.format((invoiceTotal) * 99 / 100));//getRetail_discount()

    } else {
        hm.put("invoiceDiscount", "");
    }
    hm.put("gross_total", nf.format(invoiceTotal));
    hm.put("invoiceTotal", nf.format(((invoiceTotal) * (100 - 99) / 100)));//getRetail_discount()
    hm.put("salesPersonName", "rep");
    hm.put("salesPersonContactNo", "0772189584");

    JTable jTable1 = new JTable();
    jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {},
            new String[] { "ITEMCODE", "DESCRIPTION", "QTY", "FREEQTY", "PRICE", "AMOUNT" }));
    String reportSource = "./ireports/invoice.jrxml";
    DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
    try {
        JasperReport jr = JasperCompileManager.compileReport(reportSource);
        JasperPrint jp = JasperFillManager.fillReport(jr, hm, new JRTableModelDataSource(dtm));
        JasperPrintManager.printReport(jp, false);
    } catch (JRException ex) {
        Logger.getLogger(GetInvoice.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("1");
}

From source file:NumFormat2.java

/** The main (and only) method in this class. */
public static void main(String[] av) {
    // Get a format instance
    NumberFormat form = NumberFormat.getInstance();

    // Set it to look like 999.99[99]
    form.setMinimumIntegerDigits(3);//from w w  w .jav  a  2s  .com
    form.setMinimumFractionDigits(2);
    form.setMaximumFractionDigits(4);

    // Now print using it.
    for (int i = 0; i < data.length; i++)
        System.out.println(data[i] + "\tformats as " + form.format(data[i]));
}

From source file:MainClass.java

public static void main(String[] av) {
    double data[] = { 0, 1, 22d / 7, 100.2345678 };
    NumberFormat form = NumberFormat.getInstance();

    // Set it to look like 999.99[99]
    form.setMinimumIntegerDigits(3);/*ww w. j  av  a 2 s  . c  om*/
    form.setMinimumFractionDigits(2);
    form.setMaximumFractionDigits(4);

    // Now print using it.
    for (int i = 0; i < data.length; i++)
        System.out.println(data[i] + "\tformats as " + form.format(data[i]));
}

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
    textField1.setFormatterFactory(new AbstractFormatterFactory() {
        @Override/*from   w ww  .ja v  a2 s . c  o  m*/
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
    attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
    final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01));
    textField2.setFormatterFactory(new AbstractFormatterFactory() {

        @Override
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
    textField2.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            double t1a1 = (((Number) textField2.getValue()).doubleValue());
            if (t1a1 > 100) {
                textField2.setFont(new Font(attributes));
                textField2.setForeground(Color.red);
            } else {
                textField2.setFont(new Font("Serif", Font.BOLD, 16));
                textField2.setForeground(Color.black);
            }
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(textField1, BorderLayout.NORTH);
    frame.add(textField2, BorderLayout.SOUTH);
    frame.setVisible(true);
    frame.pack();
}

From source file:br.com.thiagomoreira.bancodobrasil.Main.java

/**
 * @param args//from ww w. jav a  2 s . co  m
 */
public static void main(String[] args) throws Exception {
    if (args != null) {
        NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("pt", "BR"));

        formatter.setMaximumFractionDigits(2);
        formatter.setMinimumFractionDigits(2);

        double total = 0;

        for (String arg : args) {
            File input = new File(arg);
            if (input.exists()) {
                List<String> lines = IOUtils.readLines(new FileInputStream(input), "ISO-8859-1");

                Parser parser = new DefaultParser();

                List<Transaction> transactions = parser.parse(lines);

                TransactionList transactionList = new TransactionList();
                transactionList.setStart(parser.getStartDate());
                transactionList.setEnd(parser.getEndDate());
                transactionList.setTransactions(transactions);

                CreditCardAccountDetails creditCardAccountDetails = new CreditCardAccountDetails();
                creditCardAccountDetails.setAccountNumber("7616-3");
                creditCardAccountDetails.setAccountKey(parser.getAccountKey());

                CreditCardStatementResponse creditCardStatementResponse = new CreditCardStatementResponse();
                creditCardStatementResponse.setAccount(creditCardAccountDetails);
                creditCardStatementResponse.setCurrencyCode("BRL");
                creditCardStatementResponse.setTransactionList(transactionList);

                Status status = new Status();
                status.setCode(Status.KnownCode.SUCCESS);
                status.setSeverity(Status.Severity.INFO);

                CreditCardStatementResponseTransaction statementResponse = new CreditCardStatementResponseTransaction();
                statementResponse.setClientCookie(UUID.randomUUID().toString());
                statementResponse.setStatus(status);
                statementResponse.setUID(UUID.randomUUID().toString());
                statementResponse.setMessage(creditCardStatementResponse);

                CreditCardResponseMessageSet creditCardResponseMessageSet = new CreditCardResponseMessageSet();
                creditCardResponseMessageSet.setStatementResponse(statementResponse);

                SortedSet<ResponseMessageSet> messageSets = new TreeSet<ResponseMessageSet>();
                messageSets.add(creditCardResponseMessageSet);

                ResponseEnvelope envelope = new ResponseEnvelope();
                envelope.setUID(UUID.randomUUID().toString());
                envelope.setSecurity(ApplicationSecurity.NONE);
                envelope.setMessageSets(messageSets);

                double brazilianRealsamount = parser.getBrazilianRealsAmount();
                double dolarsAmount = parser.getDolarsAmount();
                double cardTotal = dolarsAmount * parser.getExchangeRate() + brazilianRealsamount;
                total += cardTotal;

                System.out.println(creditCardAccountDetails.getAccountKey());
                System.out.println("TOTAL EM RS " + formatter.format(brazilianRealsamount));
                System.out.println("TOTAL EM US " + formatter.format(dolarsAmount));
                System.out.println("TOTAL FATURA EM RS " + formatter.format(cardTotal));
                System.out.println();

                if (!transactions.isEmpty()) {
                    String parent = System.getProperty("user.home") + "/Downloads";
                    String fileName = arg.replace(".txt", ".ofx");
                    File output = new File(parent, fileName);
                    FileOutputStream fos = new FileOutputStream(output);

                    OFXV1Writer writer = new OFXV1Writer(fos);
                    writer.setWriteAttributesOnNewLine(true);

                    AggregateMarshaller marshaller = new AggregateMarshaller();
                    marshaller.setConversion(new MyFinanceStringConversion());
                    marshaller.marshal(envelope, writer);

                    writer.flush();
                    writer.close();
                }
            }
        }
        System.out.println("TOTAL FATURAS EM RS " + formatter.format(total));
    }

}

From source file:voldemort.server.protocol.hadoop.RestHadoopFetcher.java

public static void main(String[] args) throws Exception {
    if (args.length < 5)
        Utils.croak("USAGE: java " + RestHadoopFetcher.class.getName()
                + " [url] [keytab location] [kerberos username] [kerberos realm] [kerberos kdc]");

    long MAX_BYTES_PER_SECOND = 1024 * 1024 * 1024;
    long REPORTING_INTERVAL_BYTES = VoldemortConfig.REPORTING_INTERVAL_BYTES;
    int BUFFER_SIZE = VoldemortConfig.DEFAULT_BUFFER_SIZE;

    String url = args[0];/*from w w  w .j  a va  2s .  c  o  m*/
    String keytabLocation = args[1];
    String kerberosUser = args[2];
    String realm = args[3];
    String kdc = args[4];

    // login
    RestHadoopAuth restAuth = new RestHadoopAuth(realm, kdc, kerberosUser, keytabLocation);
    restAuth.start();

    RestHadoopFetcher fetcher = new RestHadoopFetcher(null, MAX_BYTES_PER_SECOND, REPORTING_INTERVAL_BYTES,
            BUFFER_SIZE, 0, 3, 1000);

    // start file fetching
    long start = System.currentTimeMillis();
    File location = fetcher.fetch(url, System.getProperty("user.home") + File.separator + start);

    // complete file fetching; print stats
    long size = location.length();
    double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    System.out.println(
            "Fetch to " + location + " completed: " + nf.format(rate / (1024.0 * 1024.0)) + " MB/sec.");

    // logout
    restAuth.stop();
}

From source file:voldemort.store.readonly.fetcher.HdfsFetcher.java

public static void main(String[] args) throws Exception {
    if (args.length < 1)
        Utils.croak("USAGE: java " + HdfsFetcher.class.getName()
                + " url [keytab location] [kerberos username] [hadoop-config-path]");
    String url = args[0];/*from   w  w w .  j  av  a2  s  . c om*/

    String keytabLocation = "";
    String kerberosUser = "";
    String hadoopPath = "";
    if (args.length == 4) {
        keytabLocation = args[1];
        kerberosUser = args[2];
        hadoopPath = args[3];
    }

    long maxBytesPerSec = 1024 * 1024 * 1024;
    Path p = new Path(url);

    final Configuration config = new Configuration();
    final URI uri = new URI(url);
    config.setInt("io.file.buffer.size", VoldemortConfig.DEFAULT_BUFFER_SIZE);
    config.set("hadoop.rpc.socket.factory.class.ClientProtocol", ConfigurableSocketFactory.class.getName());
    config.setInt("io.socket.receive.buffer", 1 * 1024 * 1024 - 10000);

    FileSystem fs = null;
    p = new Path(url);
    HdfsFetcher.keytabPath = keytabLocation;
    HdfsFetcher.kerberosPrincipal = kerberosUser;

    boolean isHftpBasedFetch = url.length() > 4 && url.substring(0, 4).equals("hftp");
    logger.info("URL : " + url + " and hftp protocol enabled = " + isHftpBasedFetch);

    if (hadoopPath.length() > 0 && !isHftpBasedFetch) {
        config.set("hadoop.security.group.mapping", "org.apache.hadoop.security.ShellBasedUnixGroupsMapping");

        config.addResource(new Path(hadoopPath + "/core-site.xml"));
        config.addResource(new Path(hadoopPath + "/hdfs-site.xml"));

        String security = config.get(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION);

        if (security == null || !security.equals("kerberos")) {
            logger.info("Security isn't turned on in the conf: "
                    + CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION + " = "
                    + config.get(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION));
            logger.info("Fix that.  Exiting.");
            return;
        } else {
            logger.info("Security is turned on in the conf. Trying to authenticate ...");
        }
    }

    try {

        // Get the filesystem object
        if (keytabLocation.length() > 0 && !isHftpBasedFetch) {
            UserGroupInformation.setConfiguration(config);
            UserGroupInformation.loginUserFromKeytab(kerberosUser, keytabLocation);

            final Path path = p;
            try {
                logger.debug("I've logged in and am now Doasing as "
                        + UserGroupInformation.getCurrentUser().getUserName());
                fs = UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<FileSystem>() {

                    public FileSystem run() throws Exception {
                        FileSystem fs = path.getFileSystem(config);
                        return fs;
                    }
                });
            } catch (InterruptedException e) {
                logger.error(e.getMessage());
            } catch (Exception e) {
                logger.error("Got an exception while getting the filesystem object: ");
                logger.error("Exception class : " + e.getClass());
                e.printStackTrace();
                for (StackTraceElement et : e.getStackTrace()) {
                    logger.error(et.toString());
                }
            }
        } else {
            fs = p.getFileSystem(config);
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("IOException in getting Hadoop filesystem object !!! Exiting !!!");
        System.exit(-1);
    } catch (Throwable te) {
        te.printStackTrace();
        logger.error("Error thrown while trying to get Hadoop filesystem");
        System.exit(-1);
    }

    FileStatus status = fs.listStatus(p)[0];
    long size = status.getLen();
    HdfsFetcher fetcher = new HdfsFetcher(null, maxBytesPerSec, VoldemortConfig.REPORTING_INTERVAL_BYTES,
            VoldemortConfig.DEFAULT_BUFFER_SIZE, 0, keytabLocation, kerberosUser, 5, 5000);
    long start = System.currentTimeMillis();

    File location = fetcher.fetch(url, System.getProperty("java.io.tmpdir") + File.separator + start,
            hadoopPath);

    double rate = size * Time.MS_PER_SECOND / (double) (System.currentTimeMillis() - start);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    System.out.println(
            "Fetch to " + location + " completed: " + nf.format(rate / (1024.0 * 1024.0)) + " MB/sec.");
    fs.close();
}

From source file:Main.java

public static String toNumberFormat(long value) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(0);
    return nf.format(value);
}

From source file:Main.java

public static String getNumberWithFractionDigit(double value, int fracLength) {
    NumberFormat nf = NumberFormat.getInstance();

    nf.setMaximumFractionDigits(fracLength);
    nf.setMinimumFractionDigits(fracLength);

    return nf.format(value);
}

From source file:Main.java

public static String currencyFormat(double value, int fractionDigits) {
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    nf.setMaximumFractionDigits(fractionDigits);
    return (nf.format(value));
}