Printing a double to accuracy of 2 decimal places

Hi,
I have a double value and I want to print it to an accuracy of 2 decimal places. Is there any way to do this. I tried using the DecimalFormat by
doing the following
String str = Double.toString(value);
DecimalFormat dec = new DecimalFormat(str);
dec.setMaximumFractionDigits(2);
String res = dec.toString();But this doesn't seem to work. I am using java 1.4.
Thanks

You can use DecimalFormat but like this:
        double value = 1.345678d;
        System.out.println(value);
        DecimalFormat dec = new DecimalFormat("0.00");
        String result = dec.format(value);
        System.out.println(result);Or you can use a BigDecimal where you can specify the most appropriate rounding method:
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(bd.toString());HTH,
Christian

Similar Messages

  • How to change a double to 2 or less decimal places

    hi
    im trying to change a double to 2 decimal places
    the reason is i have a angle that is sesitive to 1.0 x14
    and it look rediculas to look at :)
    i think on a calculater you use E exponents
    but im unsure.

    There's a DecimalFormat class. And also Formattable interface. Classes implenting the latter can be formatted using a Formatter which employs the notation common in C and other languages.
    String has a format() method that allows a formatted string to be produced, and there are numerous printf() methods in PrintWriter, Console etc
    public class RoundingEg {
        public static void main(String[] args) {
            double pi = Math.PI;
                // %.2f means "floating point number with 2 dp"
                // %n means "ewline"
            System.out.printf("%.2f%n", pi);
                // or to obtain a string
            String displayStr = String.format("%.2f", pi);
            System.out.println("Used as any other string: " + displayStr);
    }

  • Double value truncated to two decimal places without rounding the value.

    I want to truncate double value to two decimal places without doing the rounding of the value.
    Is there any method which can directly do the truncation.

    There's many ways to achieve this such as using
    BigDecimal's setScale method or type-casting. This is
    the way I like to do it:double d = -5.239;
    d = d > 0 ? Math.floor(d * 100) / 100.0 : Math.ceil(d
    * 100) / 100.0;
    Your division by 100 may cause an rounding error, because there are numbers which no finite binary representation. That's splitting hairs! I know ;-)

  • Printing exactly 2 decimal places

    I'm trying to print my double type variables to exactly 2 places. but numbers such as 3.00 and 124.00 keep printing as 3.0 and 124.0. Is there an easy way to force the printing to two decimal places on a primitive double type value without having to cast it to a Double object and playing around with NumberFormat and all that entails?
    thanks much,
    jh

    darelln has exactly the right answer, except that you must do the thing you don't want to do. If it were me, I'd go with his example. It's less work and much cleaner.
    import java.text.*;
    public class DoubleTest {
    static double[] numbers = {3000, 124.12, 123.122, 3.0, 124.0, 10.2, 12.14, 1234.55};
    static final NumberFormat f = new DecimalFormat("#.00");
        public static void main(String [] args) {
            System.out.println("Goofy way!\n");
            for (int i=0 ; i<numbers.length ; i++) {
                printD(numbers);
    System.out.println("\nRight way!\n");
    for (int i=0 ; i<numbers.length ; i++) {
    System.out.println(f.format(numbers[i]));
    static void printD(double dbl) {
    if (dbl % 10 == 0) {
    System.out.println(dbl + "0");
    } else {
    String sdbl = "" + dbl;
    String predot = sdbl.substring(0, sdbl.indexOf("."));
    String atdot = sdbl.substring(sdbl.indexOf("."), sdbl.length());
    String postdot = sdbl.substring(sdbl.indexOf(".") + 1, sdbl.length());
    if (postdot.length() == 2) {
    System.out.println(sdbl);
    } else if (postdot.length() < 2) {
    System.out.println(predot + "." + postdot.substring(0,1) + "0");
    } else {
    System.out.println(predot + "." + postdot.substring(0,2));
    java DoubleTest
    Goofy way!
    3000.00
    124.12
    123.12
    3.00
    124.00
    10.20
    12.14
    1234.55
    Right way!
    3000.00
    124.12
    123.12
    3.00
    124.00
    10.20
    12.14
    1234.55
    and the results are identical!

  • Rounding up decimal places

    Hi,can anyone please tell me how to round up a double type value to 6 decimal places.
    Thank You!

    You should be able to adapt this solution I posted last week:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=412237
    Changing the int's to double's will probably work fine.
    Cheers,
    Radish21

  • Print Doubles to two decimal places?

    When I do calculations on my double numbers and then print them on screen I get a string of digits after the decimal point. Can anyone give me the code as to how I use the DecimalFormat class to make these digits print to 2 decimal places. I am sure it is very simple line or two of code but I am unsure how.
    Thanks

    double number = 123456.789;
    DecimalFormat df = new DecimalFormat("#,##0.00");
    System.out.println(df.format(number));
    DesQuite

  • Print Scale Percentage - Can the percentage go more than 2 decimal places??

    Hello All,
    Illustrator CS6
    I want to know if it is possible to get more than 2 decimal places in the Print Scale Percentage option box (as shown below)?
    It seems to round to 2 and I would like to get at least 3 for better accuracy.
    Any thoughts?
    Thanks
    Geoff

    Not that I know of. If you need it to be more exact, resize the artboard and scale the content. It's an arguable point, anyway, given how your printer will translate/ rasterize the stuff. Even if there were more digits, the result after the halfftoning might not at all be any different...
    Mylenium

  • How can I limit a double value to two decimal place?

    How can I limit a double value to two decimal place?
    Java keeps on adding zero's to a simple double subtraction:
    1497 - 179.64 = 1317.3600000000001The answer must have been simply: 1317.36

    If the trouble is with output ...
    If the trouble is with value accuracy ...The trouble is with OPs understanding of and/or expectations of IEEE 754 floating point numbers. o_O
    [And it's probably a view (output) issue.]
    how can i actually use numberformat to cut those
    unwanted decimal places?Read the API - Puce already provided the link.

  • A double with 2 decimal places

    I need to output a double that has 2 decimal places. The default is just one and I don't know the command to make it two. For example,i want an output of 37.5 to be displayed as 37.50. If you know the command, please tell me. Thanks!

    Looks like you are trying to deal with money.
    Firstly if you are dealing with money store everything as the lowest form of currency in your given area. eg as pence or cents and place it in a int or long. That way you dont get any rounding erros when you multiply up the value.
    To put two decimal places on a number is easy just use a DecimalFormat from java.text
    Like this
    double myNumber = 3.1;
    DecimalFormat decF = new DecimalFormat( "######0.00" );
    String myFormattedNumber = decF.format( myNumber );
    System.out.print( "My number is " + myFormattedNumber ); The #######0.00 in the DecimalFormat constructor call is a pattern that is used to format the number. The # indicate an optional number the 0 indicates a required number and if one is not provided a 0 will be included.

  • Printing to 2 decimal places

    i have my database in mysql and my field total is declared as decimal to 2 decimal place.....how to i get it to print to two decimal place in my JSP page...i have declared the variable as double but when it is printing it is printing to one decimal place only...please help

    don't declare ur column as decimal in MySQL . Declare as decimal(3,2);
    thanx,
    Samir

  • Formatting a Double to 2 decimal places without first converting to String

    Hi,
    Does anyone have any clear idea on how to format a Double directly without first converting it
    to a String.I have just read through DecimalFormat/NumberFormat but I think there might be an easier way.I am also aware of printf(%f) and format(%f),but unfortunately am using Java 1.4 at the moment which does not seem to support them(will upgrade soon).The code I have is as follows:
    public void displayAnalysis ()
           System.out.println ("========================================================================");
           System.out.println ("========================================================================");
           System.out.println ("\nANALYSIS RESULTS FOR FILE " + inputFile + " \n");
           System.out.println ("========================================================================");
           System.out.println ("========================================================================");
           System.out.println ("\nString length: "+ inputText.length());
           System.out.println ("Ratio of printing to non-printing characters: "+ pRatio);
           System.out.println ("Ratio of vowels to consonants: "+ vRatio);
           System.out.println ("");
           System.out.println ("Frequency of vowels as a percentage of number of printing characters;");
           System.out.println ("Percentage of a's ="+ (NumberFormat.format(new DecimalFormat(((double)frequency[0]*100)/printable)))));
           System.out.println ("Percentage of e's ="+ ((double)frequency[1]*100)/printable + "%");
           System.out.println ("Percentage of i's ="+ ((double)frequency[2]*100)/printable + "%");
           System.out.println ("Percentage of o's ="+ ((double)frequency[3]*100)/printable + "%");
           System.out.println ("Percentage of u's ="+ ((double)frequency[4]*100)/printable + "%");
           System.out.println ("Number of whitespace characters were " + whitespace);
           System.out.println ("");
           System.out.println ("========================================================================");
           System.out.println ("========================================================================");
           System.out.println ("");
           System.out.println ("");
       }I would like to display the frequencies to 2 decimal places.As a last resort I will have to alter the code to use DecimalFormat,but I'm hoping someone has a simpler solution.

    Oops,please ignore the line for the first frequency (a's),I was just playing around with trying to use NumberFormat!

  • PO print preview displays incorrect setting in decimal places

    Dear Experts
    Please help me on the following condition.
    I have a problem in print preview of a PO. It displays the incorrect setting for decimal place in currency.
    It shows USD 1.404,00 whereby the amount should be USD 1,404.00
    This only happens to a certain vendor that is doing PO for the first time from that country
    Example:
    I'm creating a PO for vendor 123. Vendor 123 is located in country A. No PO has been created for any
    vendor in country A before. When I saved my PO, in print preview, the decimal setting is not correct.
    But when I'm creating another PO, for vendor 234. Vendor 234 is located in country B. There have been
    several POs created for vendors in country B before. When I saved my PO, in print preview, the decimal
    setting is correct.
    Both vendor 123 and vendor 234 is using currency of USD.
    Is there any other setting with the vendor master in regard with the currency decimal setting for each
    country for the vendor? Or something that I've missed out?
    Diagnosis:
    I've checked with the user profiles->default-> decimal notation. It displays 1,234,567.89 correctly
    I've also run OY04, but the decimal setting is correct.
    Thank you
    Regards
    Syukri

    this has nothing to do with print preview, it is just basic country setting (OY01) how a quantity and value is written on a PO to a vendor is country xyz.
    German uses to comma to seperate decimals, while USA uses the point to seperate decimals
    this would be the German version 1.404,00, and this the US version:: 1,404.00
    so if an American sends a PO to a German vendor, then the document will show 1.404,00 so that the German can understand that he wants 1404. (and not 1000 times less)

  • Decimal places in doubles

    Hi,
    How do you limit the number of decimal places which are displayed by a double??
    Cheers
    David

    http://java.sun.com/docs/books/tutorial/i18n/format/index.html

  • I can't print a double sided paper

    I can't print a double sided project, I don't know what I am doing wrong.

    If your printer doesn't do two sided printing (most don't) print the odd pages first, then flip the paper over and print the even pages.  You will have to experiment to see how to flip the paper.
    I do it by printing page 1, then flipping page one over and putting it back into the paper tray.
    Then I print pages 2 and 3.
    Remove the the completed page 1 and 2.
    Flip page 3 over and print pages 4 and 5.
    Repeat the process until you are done.

  • Printing on Double A4 or Panoramic paper

    The spec for my Photosmart Prrmium 309 g says it will print on "Double A4" paper - which is 8.3 inch by 23.4 inch. But I can't figure out any way to do this. The printer driver does not offer this size paper as an option. If I set it up as a custom paper, the printer sends back a paper size error.
    Has anybody succeeded with this?

    Hi - Not sure which printer you have, but if the paper type is set to "Automatic", try choosing "Plain Paper".  Depending on the printer, this should shut off the paper sensor.
    Hope that helps.
    Say Thanks by clicking the Kudos thumbs up. Please mark the post that solves your problem as an Accepted Solution so other forum users can utilize the solution.
    I am an HP employee.

Maybe you are looking for

  • How do I move all clips from an event into the edit line...

    If I have an event of tons of clips that comprise an hour of footage, how can I select all of those clips at once from the event library and transfer them to the edit line above? There is no Select All feature, that I can see, and it takes forever to

  • Itunes does not pass windows logo testing to verify CD/DVDrom drives, Why?

    Hello All, When I try to install Itunes 9.2 on my XP 32bit machine, I get the error message "Itunes does not pass windows logo testing to verify CD/DVD rom drives this software will not be installed. Contact your administrator" I am the owner & my ac

  • Lost 2 Gb from my iCloud

    Hello, can anyone please explain the issue? I have a 2.1 GB of iPhone backup on icloud and it hows me that my icloud drive is full... I have even erased my icloud account and started from scratch but still missing around 2 GB... I tried everything...

  • BSP Batch-Input

    Hi Guys, i have ZTable and need upload CSV from BSP web page. Before upload, code need delete Table data. In BSP only need request Patch for CSV File in PC. Any example or idea for fix this problem ?

  • HT3509 I have no erase button in my window?

    Where it says there should be an erase tab at the top of my window, there is no tabs at all. It only shows display tabs and eject.