Formatting double

I need to format a double value without any precision
It can have 13 digits to the left of decimal and 6 digits right side of decimal.
I used
     public static String formatDouble(double dNumber) {
          DecimalFormat dcf = new DecimalFormat("##################0.000000");
          String sformattedDouble = dcf.format(dNumber);
          return sformattedDouble;
Now the problem is that the DecimalFormat class uses ROUND_HALF_EVEN rounding, which I do not want to use.Should I be using some other data type(like BigDecimal) instead as the numbers I am dealing with are pertaining to currency values so I can not use precision ?
Any suggestion will be great.

Sorry I meant.....I do not want it to be rounded off
e.g. If I use it in following way I get
999999999999.000000 as output
     public static void main(String args[]) {
          double dbl = 999 999 999 998.999 999;
          System.out.println(formatDouble(dbl));
You are trying to place a number with 18 decimal places in a double which only hold about 17 decimal places so the conversion to 999999999999 get done before you try to use it. If you realy need this sort of precision then you could try BigDecimal but be prepared for a big performance penalty.

Similar Messages

  • Noise while formatting double numbers

    Hi all,
    When I try to format a number with 10 to 12 decimal point, I get noise as the number gets bigger. I know this is because computer can not handle all the floating point numbers when converted to binary. I wanted to see if any one know how to find out how many decimal points I can saw for perticular number with out getting noise at the end. For example, if you try to format double number like 99999.99 using snprintf and try to have 12 decimal points them you get 99999.990000000005. Is there any way to avoid this and work around.
    Thanks...

    Look up the DecimalFormatter/NumberFormatter APIs.
    Steve

  • Formating double number

    hi all. I have problems print numbers > 999999 in double format:
    public class P {
         public static void main(String arg[]) {
              double d=234345*2532.34;
              System.out.println(d);
    }output: 5.934412173000001E8
    how can i print amplified format: "593441217.3"?
    thanks.

    import java.text.DecimalFormat;
    public class P {
         public static void main(String arg[]) {
              double d=234345*2532.34;
              DecimalFormat df = new DecimalFormat("#############.##");
              System.out.println(df.format(d));
    }output its ok
    thanks hunter
    can i quit this limits ( now limit is 13 int and 2 decimal positions).?

  • Formatting Double value.

    Hai all,
    Please help me in this........
    I have to set Double value in JTable with two fraction digit (example: 111.00)
    I tried fromatters but all formatters returning a String.
    I f set as a string it shows me as 111.00 If i set as a Double It shows me as 111.0.
    help me in this.
    Regards,
    Suresh Dhandauthapani.

    I'm writing a loop that tallies a series of values and
    then I have to calculate the percentages and display
    itSo you have number array?
    1st loop: get the total
    2nd loop:
    a. calculate the percentage
    b. format the result using java.text.DecimalFormat
    c. display it
    >
    It would be nice if I could simply write a for loop
    that will output this data
    using flowlayout.
    No, use java.awt.GridLayout and drop the (formatted) results onto an array of labels in the second loop.

  • Formatting double type output

    Hi all,
    can anyone teach me how to format the output of a double data type in the console?
    let's say i have:
    double myNum = 1.234567890123;if i want only four digits after the decimal point (ex. 1.2345), how am i supposed to do it?
    thanx a lot!

    i mean, how do i convert it from 10 digits to the
    right of the decimal point to become only four?
    when i was learning C, we simply put:
    printf("The number is: %2.4f"+myNum);
    is there any similar way on how doing it? because i
    have a lot of double number to be printed out, and if
    i dont limit the format, my screen was flooded!
    thanx a lot!And the DecimalFormat class does that for you. Look at the following:
    DecimalFormat myFormatter = new DecimalFormat( "###.####" );
    String output = myFormatter.format(value);
    System.out.println("Without formatting, value == " + value + ", with formatting, value ==  " + output);� {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to format double to currency format?

    I have this code and I keep trying to convert it to currency, but doesn't work. Please help ...
    double price = new Double(content.toString()).doubleValue();

    NumberFormat nf = NumberFormat.getCurrencyInstance();
    String currency = nf.format(yourDoubleHere);make sure u import java.text.NumberFormat;

  • Formatting Doubles with Scientific Notation Depending on Exponent Size

    Hi there. I was just wondering if there was a better way to do the following:
    DecimalFormat fmt;
    if (v>=1.0E9 || v<=-1.0E9 || (v>-1.0E-8 && v<1.0E-8 && v!=0.0 && v!=-0.0))
         fmt = new DecimalFormat("0.########E0");
    else fmt = new DecimalFormat("0.########");
    return fmt.format(v);

    I'm not an expert on DecimalFormat, so I may have missed something, but the only improvement I can see is to remove the v!=-0.0 check. 0.0==-0.0, so it's unnecessary.

  • Format double

    I have a program that converts units of measurement. Problem is, it's outputting numbers like "6.2E-7" when the user converts things such as milimeters > miles. I want it to be rounded to a readable decimal (Preferably without using BigDecimal), but DecimalFormat seems to not be working. Any suggestions?
    My DecimalFormat:
    private final DecimalFormat decForm = new DecimalFormat("#0.000000");EDIT: Just to give you an idea of the numbers I'm trying to divide,
            Milimeter(0.03937007874015748031496062992126D),
            Centimeter(0.3937007874015748031496062992126D),
            Decimeter(3.937007874015748031496062992126D),
            Meter(39.37007874015748031496062992126D),
            Kilometer(39370.07874015748031496062992126D),
            Inch(1D),
            Foot(12D),
            Yard(12D * 3D),
            Mile(5280D * 12D);The system is based on how many inches each unit is, to keep simplicity.
    Edited by: Jadz_Core on Feb 26, 2010 9:33 PM

    But if you insist,
    public class UnitConverter  {
        private double convert(Type from, Type to, double value) {
            if (from.getInches() < to.getInches()) {
                value = (from.getInches() / to.getInches()) * value;
            } else if (from.getInches() > to.getInches()) {
                value = (from.getInches() / to.getInches()) * value;
            return value;
        private enum Type {
            Milimeter(0.03937007874015748031496062992126D),
            Centimeter(0.3937007874015748031496062992126D),
            Decimeter(3.937007874015748031496062992126D),
            Meter(39.37007874015748031496062992126D),
            Kilometer(39370.07874015748031496062992126D),
            Inch(1D),
            Foot(12D),
            Yard(12D * 3D),
            Mile(5280D * 12D);
            Type(double inches) {
                this.inches = inches;
            private double inches;
            public double getInches() {
                return inches;
        public static void main(String args[]) {
            System.out.println(new asdasd().convert(Type.Milimeter, Type.Mile, 1));
        // Variables declaration - do not modify
        private javax.swing.JButton conButton;
        private javax.swing.JTextField fromBox;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JSeparator jSeparator1;
        private javax.swing.JTextField solutionBox;
        private javax.swing.JComboBox type1;
        private javax.swing.JComboBox type2;
        // End of variables declaration
    }Edited by: Jadz_Core on Feb 26, 2010 10:18 PM
    Edited by: Jadz_Core on Feb 26, 2010 10:19 PM

  • Formatting custum double precision

    I don't understand the DecimalFormat API.
    I need to format double variables trajectory_angle, velocity_fps and elapsed_time to three decimal place precision round off in the following code segment. For example, the value of elapsed_time would change from 1234.56789 to 1234.568 in results_string. Note that I need to set this precision only in this method since I wish to retain prior precision determined in other parts of the code prior to this method being invoked. Please examine this segment and indicate what corrections I need to make.
         public String results()
         DecimalFormat df = new DecimalFormat(.###);
         results_string =
         "Distance =\t\t" + distance / 5280.0 + " miles\n"
         + "Altitude =\t\t" + altitude + " feet\n"
         + "Trajectory Angle =\t" + df.format(trajectory_angle) + " degrees\n"
         + "Velocity =\t\t" + df.format(velocity_fps) + " feet per second\n"
         + "Elapsed Time =\t\t" + df.format(elapsed_time) + " seconds\n";
         return results_string;

    Nevermind. I found the solution. However, I need to see better examples on how to use that API.

  • How can I format the double value?

    Hi,
    I am trying to format the double variable as like,
    double var = 1234.56789
    but i want that variable as like var = 1234.56
    How can i do that in java?
    Please help me.
    From
    Parshuram Walunjkar

    Try something like the following, assume the variable 'd' underneath is your double value that you want to format.
    double d = 4.45678;
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(5);
    nf.setMinimumFractionDigits(5);
    String number = nf.format(d);
    Then use the string "number" for printing out.

  • Help needed : Formatting a double using Decimal Format

    Hi Everyone,
    I am having trouble formatting doubles. Basically I recieve a double and an int that represents the number of decimal places.
    From this I have to round the double. This is no problem, and is carried out as follows:
    public static String roundDouble(double d, int scale){
    BigDecimal big_decimal = new BigDecimal(d);
    java.text.DecimalFormat formatter = new java.text.DecimalFormat();
    formatter.applyPattern("########.#######");
    double dubble = big_decimal.setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    return formatter.format(dubble,new StringBuffer(),new java.text.FieldPosition(formatter.FRACTION_FIELD)).toString();
    This work fine for me. (I use a DecimalFormatter to convert exponential in to actual). However my problem is that when my colleuge uses this method from a different locale it all goes wonky.
    In my locale of UK given something like 0.92742999999999 with 4 dp I get
    0.9274. In his locale which is Germany, he gets 0,9274.0000
    I assume I need to use DecimalFormatter.applyLocalizedPattern, but what should the pattern be?
    regards,
    dr_n35s

    formatter.applyPattern("########.#######");# before the decimal point have no effect on the format.
    This work fine for me. (I use a DecimalFormatter to
    convert exponential in to actual). However my problem
    is that when my colleuge uses this method from a
    different locale it all goes wonky.
    In my locale of UK given something like
    0.92742999999999 with 4 dp I get
    0.9274. In his locale which is Germany, he gets
    0,9274.0000The pattern for the UK should be ".#######"
    The pattern for DE should be ",#######"
    I assume I need to use
    DecimalFormatter.applyLocalizedPattern, but what
    should the pattern be?You can't hard code values into your code, use a properties file to localize your program.

  • Need help with formating numbers

    public void returnDollars()
              double dollar;
              dollar=amountr-amount;
    NumberFormat fmt = NumberFormat.getNumberInstance();
              System.out.println(fmt.fomat(dollar));
    there is my code.....now lets say
    amountr = 10
    amount 8.5
    now when i print my dollar amount i want it to show up as 1 not 1.5 or 2. So in other words format it with no decimals and not round up at the same time.
    Help would be appriciated...thanks

    well...after 8 hours of trying to get it working i did it.....here it is ...........I'm sure there are many ways to make it smaller.
    import java.text.*;
    import java.io.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    public class Cashier
    double amount;
    double amountr;
    double dollar;
    double amountleft;
    double quaters;
    double test;
    double dimes;
    double pennies;
    public void getAmount()throws IOException
         BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("Please enter amount due:");
              String input = console.readLine();
         amount = Double.parseDouble(input);
    System.out.println("Amount due = " + amount);
         public void recieve()throws IOException
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("Please enter amount recieved :");
              String input = console.readLine();
         amountr = Double.parseDouble(input);
    System.out.println("Amount recieved = " + amountr);
         public void returnDollars()throws IOException
              double check = amountr-amount;
              dollar=amountr-amount;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)dollar);
    double d = Double.valueOf(s).doubleValue();
    amountleft=check-d;
         System.out.println("Dollars to return " + s);
    public void returnQuaters()
         quaters= amountleft/.25;
         double check = quaters;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)quaters);
    double d = Double.valueOf(s).doubleValue();
    fmt.setMaximumFractionDigits(2);
    String dol = fmt.format(amountleft);
              //System.out.println(dol);
              double e =Double.valueOf(dol).doubleValue();
    e= e-2*(.25);
    amountleft=e;
         System.out.println("Quaters to return: " + s);
         public void returnDimes()
         dimes= amountleft/.1;
         double check = dimes;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)dimes);
    System.out.println("Dimes to return: " + s);
    double d = Double.valueOf(s).doubleValue();
    fmt.setMaximumFractionDigits(2);
    String dol = fmt.format(amountleft);
              double e =Double.valueOf(dol).doubleValue();
    e= e-1*(.1);
    fmt.setMaximumFractionDigits(2);
    String dola = fmt.format(e);
              double t =Double.valueOf(dola).doubleValue();
    amountleft=t;
              public void returnNickles()
         double nickles = amountleft/.05;
              double check = nickles;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)nickles);
    System.out.println("Niclkles to return: " + s);
    double d = Double.valueOf(s).doubleValue();
    fmt.setMaximumFractionDigits(2);
    String dol = fmt.format(amountleft);
              double e =Double.valueOf(dol).doubleValue();
    e= e-1*(.05);
    fmt.setMaximumFractionDigits(2);
    String dola = fmt.format(e);
              double t =Double.valueOf(dola).doubleValue();
    amountleft=t;
         public void returnPennies()
              double pennies = amountleft/.01;
    DecimalFormat fmt = new DecimalFormat("##");
    String s = fmt.format((double)(long)pennies);
    System.out.println("Pennies to return: " + s);
         public static void main(String[] a) throws IOException
              Cashier cash = new Cashier();
              cash.getAmount();
              cash.recieve();
              cash.returnDollars();
              cash.returnQuaters();
              cash.returnDimes();
              cash.returnNickles();
              cash.returnPennies();

  • XML files are being read as PBEM game file format!!

    Hello,
    I am trying to edit some .xml files in Script Editor but everytime I try to open them I am told :
    'Script Editor cannot open files in the "PBEM game file" format'
    (Double clicking the .xml file opens up the Big Bang game)
    Does anyone know how to get round this? also is Script Editor the best application to use? I want to use an editor that has colours.
    Many thanks, rob

    Script Editor has one purpose - editing and compiling AppleScript.
    I can't account for the wording of the error message, but for sure I wouldn't expect it to handle XML files directly.
    You could use AppleScript to manipulate the XML data, but that's probably not ideal either.
    What you need is a text editor. BBEdit would be my first choice, or its cheaper (read: free) sibling TextWrangler.
    Both can handle any type of text file, including syntax highlighting for many structured files including programming source code.

  • Number Formating

    Hi,
    I'm using the following code for formating a number,
         public static String formater(double value ) {
              Locale loc = new Locale("en", "US");
              NumberFormat nf = NumberFormat.getNumberInstance(loc);
              DecimalFormat df = (DecimalFormat)nf;
              df.applyPattern("###,###,###,###,##0.00");
              String output = df.format(value);
              return output;
    This is working fine for all the values, but for some scenarios, its giving errors.
    for e.g.,
         if the value is 532.875, then the result is 532.88
         but if the value is 165158.005, then the result is 165,158.00. Where as this should be 165,158.01.
    you can test this at
         http://journals.ecs.soton.ac.uk/java/tutorial/intl/datamgmt/numbers.html
    I hope this is a bug in java. Can someone please help me out in solving this error. i need it very urgently.
    Thanks in advance.
    Shiva

    Not a bug. When you think you've found a bug, the first thing to do is read the documentation and make sure you understand how it's supposed to work. According to the DecimalFormat javadoc, "half-even rounding" is used. This means that if two nearest neighbor values are equidistant, it rounds to the even value.

  • Formatting currencies and decimal places

    I'm currently using NumberFormat.getCurrencyInstance() to format numbers as currency. However, one problem I'm having is that I'd like values with no cents to be formatted with no decimal places, and any values with cents to be formatted with the usual 2 decimal places. For example:
    17 would be formatted as $17
    17.45 would be formatted as $17.45
    17.4 would be formatted as $17.40
    The last one is the tricky part--I've tried formatter.setMinimumFractionDigits(0), and this works great for the first two cases. But for the last case, the number gets formatted as $17.4.
    Basically my problem is I want a number to be formatted with zero or two decimal places and nothing in between. Is there an easy way to do this?
    Thanks in advance.

    Otherwise you are likely to find that you are getting .00 due to errors from previous calculations. You are right. Adjusted it to Locale aware
    import java.text.FieldPosition;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import java.text.ParsePosition;
    import java.util.Locale;
    public class SpecialCurrencyFormat extends NumberFormat {
        private static final long serialVersionUID = 1L;
        private final NumberFormat noDecimals;
        private final NumberFormat decimals;
        private final double maxDifference;
        private final double factor;
        public SpecialCurrencyFormat() {
         this(Locale.getDefault());
        public SpecialCurrencyFormat(Locale locale) {
         decimals = NumberFormat.getCurrencyInstance(locale);
         noDecimals = NumberFormat.getCurrencyInstance(locale);
         noDecimals.setMaximumFractionDigits(0);
         maxDifference = Math.pow(10, -decimals.getMaximumFractionDigits()) * .5;
         factor = Math.pow(10, decimals.getMaximumFractionDigits());
        @Override
        public StringBuffer format(double number, StringBuffer toAppendTo,
             FieldPosition pos) {
         double adjustedValue = (Math.round(number * factor)) / factor;
         if ((Math.abs(number - Math.round(number)) < maxDifference)) {
             return noDecimals.format(adjustedValue, toAppendTo, pos);
         } else {
             return decimals.format(adjustedValue, toAppendTo, pos);
        @Override
        public StringBuffer format(long number, StringBuffer toAppendTo,
             FieldPosition pos) {
         return noDecimals.format(number, toAppendTo, pos);
        @Override
        public Number parse(String source, ParsePosition parsePosition) {
         return decimals.parse(source, parsePosition);
        public static void main(String[] args) {
         NumberFormat nf = new SpecialCurrencyFormat(Locale.US);
         double[] values = { 10000, 1000, 100, 10, 1, 10.1, 10.01, 10.001,
              10.002, 10.003, 10.004, 10.005, 10.006, 10.007, 10.008, 10.009,
              10.010 };
         for (double value : values) {
             print(nf, value);
        private static void print(NumberFormat nf, double number) {
         String formatted = nf.format(number);
         try {
             System.out.println(number + "\tas " + formatted + "\tand back "
                  + nf.parse(formatted));
         } catch (ParseException e) {
             e.printStackTrace();
    }The value adjustedValue is needed since NumberFormat doesn't seem to round the value. It just breaks.
    Piet

Maybe you are looking for