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?

Similar Messages

  • Round off Double to 2 decimal places??

    Hi all the pro out there..
    anybody can tell me how to go about rounding off eg 5.9542 to 2 decimal places in java? i went to search in API Double class, no method that allow me to do that..
    is there any other way?
    pls advise thank you

    If the former, you can do it manually by multiplying by an appropriate number, casting to int, and then dividing by the same number.Although this won't always work.
    Suppose you want 1.125 --> 1.1
    1.125 --> 11.25 --> 11 --> 1.1 plus some epsilon, since 1.1 can't be represented exactly in base-2.Yes, I know that (I assume you knew I knew that). So, maybe the OP needs to use both methods in combination (and maybe use some rounding method [such as in the Math class] other than cast).

  • Round a number to 2 decimal places

    Hi,
    I have a computed value that returns 10 plus digits after the decimal place, exampe: 2.2482352941176.
    What is the easiest way to edit this value in TestStand to return a number that is rounded up to 2 decimal places (2.25)?
    Thanks & Regards,
    Don1.
    Solved!
    Go to Solution.

    One way to do this is to use the TestStand functions Str and Val.  The %.2f rounds the number to 2 decimal places.
    Val(Str(Locals.MyValue, "%.2f"))
    Peter

  • Rounding Doubles to Two Decimal Places

    Hi All,
    I've searched the archive and found a few different posts regarding restricting the number of decimal places in doubles. However they all suggest different methods, BigDecimal, NumberFormat etc.
    Which is the simplest method of rounding a number say 10.023445656 to 10.02?
    I tried using the java.text.NumberFormat but this turns the double into a string and I need the end result to be a double.
    Thanks

    Hi All,
    I've searched the archive and found a few different
    posts regarding restricting the number of decimal
    places in doubles. However they all suggest different
    methods, BigDecimal, NumberFormat etc.
    Which is the simplest method of rounding a number say
    10.023445656 to 10.02?
    I tried using the java.text.NumberFormat but this
    turns the double into a string and I need the end
    result to be a double.
    ThanksI ahve a small code that can do the work for u:
    import java.text.*;
    double format(double val, int dec){
        double multiple=Math.pow(10,dec);
        val=Math.round(val*multiple)/multiple;
        DecimalFormat df=new DecimalFormat("0.00");
        String format=df.format(val);
       double dval=Double.parseDouble(format);
       return dval;
    }//end of functionHope that helps!

  • 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.

  • Double to 2 decimal places

    I am putting a double variable out to a web page and also calculations on that double(a price). I am getting 4 decimal places on the original price and several decimal places on the calculations. Can anyone tell me how to round down to 2 decimal places?
    Thank you.
    Karen

    I generally use a formatter along the lines of the following. You could also use a wrapper class (Double is final, and you can't extend primitives) for Double which would incorperate this formatting. However you only need to use it when you are presenting it (or if you are persisting it to a lower precision data source, where truncation could result in larger inaccuracies creeping in).
    This also changes the ROUND_HALF_EVEN behaviour of DecimalFormat to ROUND_HALF_UP.
    Alternatively you could use BigDecimal (.setScale() to set decimal places) but there is an overhead which may be restrictive.
    class Formatter {
      public static final int DEFAULT_PRECISION = 2;
      public static final String DEFAULT_PATTERN = "#.00";
      public static final String ZEROS = "0000000000000000";
      public static String convertDoubleToString(Double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(double d) {
        return convertDoubleToString(round(d, DEFAULT_PRECISION), DEFAULT_PATTERN);
      public static String convertDoubleToString(Double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(double d, int precision) {
        return convertDoubleToString(round(d, precision), "#." + ZEROS.substring(precision));
      public static String convertDoubleToString(Double d, String pattern) {
        return new DecimalFormat(pattern).format(d.doubleValue());
      public static String convertDoubleToString(double d, String pattern) {
        return new DecimalFormat(pattern).format(d);
      private static final double round(Double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d.doubleValue() * factor)) / factor;
      private static final double round(double d, int precision) {
        double factor = Math.pow(10, precision);
        return Math.round((d * factor)) / factor;
    }

  • Rounding up to a particular decimal place

    Hi,
    I'm bringing a field into my report that uses up to eight decimal places.  I'm tasked with rounding things up to the fifth decimal.  Rather than rounding when the number is five or higher, it should always round up if it is above one.
    So for example:
    2.03827893 rounds up to 2.03828000
    11.40032180 rounds up to 11.40033000
    Any ideas on the best approach for achieving this within a Crystal formula?
    Any help would be greatly appreciated.
    Thank you.

    Hi Bob,
    Right click on the field and select "Format Field"
    In "Number" tab, select "Custom Style" then click on "Customize"
    In the Roundig box you can select the Rounding type.
    --Praveen G

  • BED & AED Round up or down without decimal places

    Dear Gurus,
    My client wants BED & AED Round up to nearest value without Decimal places.
    I am using taxinn procedure and JMOP for BED and JAOP for AED As a condition.
    I tried to tick round up in condition , but it is not workig.
    Please help.

    Hi,
    In TAXINN   T code : OBQ3  against ur condition in alternative calculation type (Calty ) column put 17.
    At the same time OB90 against ur company code put 100.
    Then ur problm will be resolved.
    Biswajit

  • Rounding a number upto two decimal places.

    Hey !
    My question is regarding the rounding of a number in such a way that answer that we get after the rouning comes upto two decimal places,no matter how small or the large the number before rounding was.
    Somebody please help me.
    thanks

    hi,
    use BigDecimal class in java.math package.
    here is some code how to do it ..
    BigDecimal bd = new BigDecimal(your number here);
    bd.setScale(2,BigDecimal.ROUND_DOWN)
    System.out.println(bd);
    hope this helps ...
    bye
    ashok

  • 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

  • Rounding a number to 2 decimal places

    Is there anyway using the Round function to get it to .2
    decimal places rather than the nearest whole figure...
    I have a table that contains product prices, some of these
    are already in a nice 2 decimal format (such as 7.99 or 12.49) but
    I also have some that are like this-43.990002 and this-8.9899998.
    What is the best way to round these to 2 decimal places?
    thanks

    Do some experimentation. If you are using numberformat you
    might not need to use round.

  • Rounding off float to 2 decimal places and returning the float

    I tried doing bigdecimal but it doesnt work. :
    BigDecimal bd = new BigDecimal(5 * 0.0394);
              retval = bd.floatValue();
              System.out.printf(" th %f\n",retval);
    I see 0.197000. I know that there are 6 places since I didnt do %.2f. However its not the printf thats important . The float I want to return must be rounded off to two decimal places.
    Thanks in advance for the help,
    sb

    Use BigDecimal.round( MathContext mc ), where the MathContext object is set to a precision value of 3;
    BigDecimal roundedBigD = myOriginalBigD.round( new MathContext( 3 ) );� {�                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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!

  • Round off quantity variable eliminating decimal places

    Hi,
      I have a variable of quan type with value = 1008.123
      I want to round it off with no decimal to be displayed.
      Please suggest.

    Hi,
      Refer
    https://forums.sdn.sap.com/click.jspa?searchID=11055268&messageID=4565374
    https://forums.sdn.sap.com/click.jspa?searchID=11055268&messageID=4721312
    https://forums.sdn.sap.com/click.jspa?searchID=11055268&messageID=2700419
    Regards
    KIran

  • Rounding off a float to two decimal places

    I want to make a function where I shall pass a float and and integer.
    The float shall have to be rounded off to a value in the integer.
    Can anyone please suggest how to round off a float.
    E.g.: if the float is 12.56890 and I want to round it off to 2 decimal places, then it should be 12.57.
    Regards
    Hawker

    I didn't mention any datatypes like float, double.True, but that is what the question is about, so you weren't answering the question. For a change.
    As I mentioned, that was just a mathematical steps to round of the floating point value. (Not in any programming languages point of view).False. You didn't mention that at all.
    This is the code for that in java.So here you are mentioning datatypes and floats for the same piece of mathematics that you have already been told, with reasons, doesn't work in floating point.
    which seems to be working fine
    Seems to. What evidence do you have that the float actually got rounded? As opposed to got displayed as rounded? Which is not what the OP asked for.
    And of course all that code seems to do is round 0.01 to two decimal places, which again is not what the OP asked for.
    For any remaining fans of this 'technique', please explain the behaviour of the following code:
         public static void     main(String[] args)
              int     count = 0, errors = 0;
              for (double x = 0.0; x < 1; x += 0.0001)
                   count++;
                   double     d = x;
                   int     scale = 2;
                   double     factor = Math.pow(10, scale);
                   d = Math.round(d*factor)/factor;
                   if ((d % 0.01) != 0.0) // if 'd' really has been rounded this should be zero
                        System.out.println(d % 0.01);
                        errors++;
              System.out.println(count+" trials "+errors+" errors");
         }

Maybe you are looking for