Rounding a double to a format

Hi,
I'm trying to get a result for a formula in the format of ##.##. The result for one equation, for example, is 10.637129724208375 and I want it to be 10.64 (round to the nearest tenth, pretty much).
Any suggestions?

aeternaly wrote:
I'm trying to get a result for a formula in the format of ##.##. The result for one equation, for example, is 10.637129724208375 and I want it to be 10.64 (round to the nearest tenth, pretty much).If it's just for display, look at DecimalFormat or String.format().
If you actually need to store values to two decimal places, you're generally better off using BigDecimal.
You can find the explanation why [url http://www.eason.com/library/math/floatingmath.pdf]here (the original) or [url http://floating-point-gui.de/]here (mybe a bit friendlier).
Winston

Similar Messages

  • Rounding up doubles to 2 decimal places

    I'm currently rounding up a double in my program using Math.round(double)
    However I want to strip any trailing zeros from the output, so:
    1.235 would round to 1.24
    but 1.00 would round to 1
    How would I go about doing this?

    Also I'm making my own function to round the doubles,
    and they are returning doubles so I cannot return a
    string.If they are returning doubles that the number of "trailing zeros" is irrelevant, as that is formating. Really you should keep the precision until you want to display it, then use the formatter above.
    What are you doing?
    I'm going to take a shot in the dark; has this got something to do with money?

  • Round a double value to a specific number of decimal places?

    Hello,
    Is there standard java function which will round a double value to a specified number of decimal places? Something like:
    double d = 4.34523;
    d = round(d, 2);
    where d is finally assigned the value of 4.34?
    Thanks!
    -exits

    No, because doubles hold values in binary (as do all values in a computer, of course, but there's no additional stuff to indicate decimal values).
    If you want values with specific rounding rules in decimal, use java.math.BigDecimal.
    If you just want to format the number with a specified number of decimal digits, use java.text.DecimalNumber.

  • 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 some help in Rounding a double value to a whole number

    Hey Peeps,
    Need some help here, I got a method that returns a value in double after a series of calculation.
    I need to know how can I round the double value, so for example,
    1. if the value is 62222.22222222, it rounds to 62222 and
    2. if the value is 15555.555555, it rounds to 15556
    How can i do this
    Zub

    Hi Keerthi- Try this...
    1. if the value is 62222.22222222, it rounds to 62222 and
    double d = 62222.22222222;long l = (int)Math.round(d * 100); // truncatesd = l / 100.0;
    double d = 62222.22222222;
    System.out.println(d);
    long l = (int)Math.round(d * 100);
    // truncatesSystem.out.println(l);
    d = l / 100.0;System.out.println(d);
    for (int i = 0; i < 1000; i++)
    {    d -= 0.1;}
    for (int i = 0; i < 1000; i++)
    {    d += 0.1;}System.out.println(d);
    regards- Julie Bunavicz
    Output:
    62222.22222222
    62222
    62222.22
    62222.22000000000001

  • Round up double to 2 decimals

    How to round up double to 2 decimals? where in API i should look up? Thank you for your help!
    e.g., Book (including tax) :14.99 + 14.99 * 10% = 16.489 ---> 16.49

         * Scale decimal number via the rounding mode BigDecimal.ROUND_HALF_UP.
         * @param value Decimal value.
         * @param scale New scale.
         * @return Scaled number.
         * @since 1.8.3
        static public double getScaled(double value, int scale) {
            double result = value; //default: unscaled
            //use BigDecimal String constructor as this is the only exact way for double values
            result = new BigDecimal(""+value).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
            return result;
        }//getScaled()

  • Exporting PDFs and maintaining double-page spread format

    I've combined a large number of individual PDF files (created in InDesign) for print.  Now I would like to create an iBook with these pages.  I've created a PDF file for use on an iPad but how do I maintain the double-page spread format?  I can view this successfully in Acrobat but not in iBooks.  Can anyone help?
    Thanks
    F

    This is best addressed in either an iBooks forum on the Apple website or InDesign. For use in iBooks you might be best off using a format other than pdf.

  • What's the best way to round a double to 12 decimals?

    What's the best way to do it? The math functions don't seem quite right...

    I'm doing three different algoritms that are mathematically identical. I'm working with precisions from 2 to 12 significants digits (working with a function I got from a book), but the results are no exctly what I expect... For example, the one with 12 significant digits is 97.45322134230000001, or something like that... I'm making a method that receiving a double and an n makes a string with the correct number of significant digits... However, rounding the double beforehand would come in handy.

  • Rounding a double

    Hi,
    What's the best (and fastest since I got lots of values) way to perform a rounding on a double value?
    I think what I'd like to do is half-up rounding, so when it should round up to 2 digits e.g., it should cut off the rest when the third position is a 0;1;2;3 or 4 and should add one to the second digit, when the third is one out of them: 5;6;7;8;9.
    I tried it myself this way. Now this has happened - at the end (converting int to double) it screws at some values - why and how can I fix that or what is a better way to do this, since this solution looks kind of goofy to me?
        public double roundValue( double dTemp, int iDigits){
             // splitting up into the pure int part of the NOT rounded value
             System.out.println("****   dTemp to round: " + dTemp);
             System.out.println("iDigits to round to: " + iDigits);
              int iIntPart = (int) dTemp;
              dTemp -= (double) iIntPart;
              System.out.println("iIntPart: " + iIntPart);
              System.out.println("dTemp - only minor digits: " + dTemp);
              // calculation of a factor for the lower digits
              double dDigits = 1.0;
              for(int cnt = 0; cnt < iDigits; ++cnt)
                  dDigits *= 10.0;
              System.out.println("dDigits: " + dDigits);
              System.out.println("dTemp * dDigits: " + (dTemp * dDigits));
              System.out.println("Math.round: " + Math.round(dTemp * dDigits));
              System.out.println("Math.round/dDigits: " + ((Math.round(dTemp * dDigits)) / dDigits));
              // processing Math.round()
              dTemp = (Math.round(dTemp * dDigits)) / dDigits;
              System.out.println("dTemp - after: " + dTemp);
              // dTemp is now rounded
              dTemp += (double) iIntPart;
              /* here sometimes, the value returns results like this - why?
               * 4.941519877284079 -> iDigits == 2 -> 4.9399999999999995
               * 5.94004582533272 -> iDigits == 2 -> 5.9399999999999995
              System.out.println("****   dTemp after adding the int part: " + dTemp);
              return dTemp;
        }

    Thanx I tried it out and I thought I had to use Math.round() the way I did. But still what happens at the conversion from an int to a double - just curious?
    I did it now this way - I thought Math.round has some probs, with the digits in front of the point:
        public double roundValue(double iValue, int iDecimalPlace) {
            double dPowerOfTen = 1;
            while (iDecimalPlace-- > 0){
               dPowerOfTen *= 10.0;
            return (Math.round(iValue * dPowerOfTen) / dPowerOfTen);
         }

  • Rounding xs:double value

    Hi in bea xquery function pallette we only foung round() for decimal type.But we had a requirement to round xs:double values.
    How can i achive this ,any method for round double values or to convert double to decimal.

    does round( $someDouble ) not work?
    Can you please try a few things yourself before posting?
    If you already have, can you please post what you have tried?

  • Rounding a double value

    What is the easiest way to round a Double variable to 2 significant figures?
    Cheers Mike

    Oh, classical and very typical question on this forum.
    The short answer is nope. You don't do that and you don't need to do that. If you really really have to must doing that, you used the wrong type - double.
    By definition, double is an approximation. No gurantee on precision lose.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Rounding a double to a nearest 5000

    HI Guys,
    I wanted to know the easy way to rounding a double number to nearest to multiples of 5000.
    Thanks
    -nicedude

    Thank you . This is sure not a swing question at all, I should not have posted it here.
    Thanks you anyway for your answer. I did exactly the same thing. i thought somebody may come up with even a brighter idea, so i posted it.
    Thank you once again for your anwer.

  • May I know how to round a double number to 2 decimal points?

    if I have a double number 135.25689951591, how can I round this number to make it output as 135.26?

    double number = 135.25689951591;
    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
    System.out.println(df.format(number));Alll this will do is display the value 135.26, number will still hold 135.25689951591

  • Rounding up doubles

    Just wondering if anyone knows how to round up a double so that for instance 100.232323 can be up to 100.
    This is due to trying to convert a price in pence to a meaningful price.
    Also is there anyway to represent a figure in pounds and pence???
    Regards.

    If you are working with money you shouldn't do floating point arithmetic. You should either use one of the following:
    1. java.math.BigDecimal. See example: double monthlyInterest = 5.5d / 1200d;
    double monthlyPayment = 700.25d;
    BigDecimal interestAmount = new BigDecimal(monthlyInterest).setScale(5,BigDecimal.ROUND_HALF_UP);
    BigDecimal principalAmount = new BigDecimal(monthlyPayment).setScale(2,BigDecimal.ROUND_HALF_UP);
    BigDecimal appliedPayment = payment.subtract(interestAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
    //to get their double values just do (for example)
    double i = interestAmount.doubleValue();
    double p = principalAmount.doubleValue();
    double payment = appliedPayment.doubleValue();2. Multiply all numbers by a power of 10 (for example 100) and then truncate or round the decimals, then do your arithmetic, then divide by the same number. To truncate, just cast your double value to an int.int newValue = (int) someDoubleValue;To round, you can use any of the java.lang.Math methods.Math.ceil(someDoubleValue);
    Math.floor(someDoubleValue);
    Math.round(someDoubleValue);You can do your own research. :)
    The reason why you should not do floating point arithmetic is because it is not accurate.

  • Reading/writing doubles in primitive format

    I created an array of doubles using random.nextDouble(). Then wrote the array to a file using a primitive format. When trying read the data and put it back into an array, it gives me a java.io.EOFException. Here's the code I used to write and read the data, not the entire program, just the code used for it. Any help is much appretiated; I've been working on this for hours.
              try {
                   DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("dblPrim.data")));
                   start = System.currentTimeMillis();
                   for(count=0; count<arraysize; count++){
                        output.writeDouble(anarray[count]);
                        ++count;
                   end = System.currentTimeMillis();
                   time = end - start;
                   displayTime(time, 1);
                   output.close();
                   average = 0;
                   total = 0;
                   start = 0;
                   time = 0;
                   end = 0;
                   double[] anarray2 = new double[arraysize];
                   DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream("dblPrim.data")));
                   start = System.currentTimeMillis();
                   for (count = 0; count<arraysize; count++){
                        System.out.println("" + input.readDouble());
                        anarray2[count] = input.readDouble();
                        total = total + anarray[count];
                   end = System.currentTimeMillis();
                   time = end - start;
                   average = total / anarray.length;
                   displayAverage(average, 2);
                   displayTime(time, 2);
                   input.close();

    take a look at your second 'for' loop:
    for (count = 0; count<arraysize; count++){
    System.out.println("" + input.readDouble());
    anarray2[count] = input.readDouble();
    total = total + anarray[count];
    }you are calling readDouble() TWICE for each iteration, so you will run out of doubles to read too quickly!!

Maybe you are looking for

  • Upgrade from 10.1 to 10.2

    dear all , if i have oracle database 10.1.0 on windows and i have another server on unix can you tell me the best method to transfer database from windows to unix ??? another question if i have 10.1.0 and i need to upgrade it to 10.2.0 what i do ???

  • Linux Drivers Redux...

    I have a MSI Mast23 2 FAR running with 1 Opteron 240s. I have Gentoo intalled ont he box.   I can't seem to get the sound working.. Which driver should I be using?  I tried the snd-via23xx (or whatever) and that doesn't find a good card.    I tried t

  • Nano Problem

    I've got a new Ipod Nano and it's worked fine until this week. I cannot "turn it on" and have tried all the trouble shooting steps. I can use the updater and when I connect, it recognizes the unit including the serial number, goes through the restore

  • Animation CoDec to DVNSTC Frame Dimension Challenge

    I have 3 videos that I need to edit together. They were provided to me as QuickTime files using the animation codec. A is 640x480 Apple Lossless codec. B is 720x486 using Animation codec. C under the format says the following "Format: None, 720x480 (

  • My apple ID is locked how to unlock it

    my apple id is locked how to unlock it