Setting double value precision

Is there any way to set the precision on a double.
Example:
double = 25.00016000207654
precision = 4 decimal places (or some value 'x')
So I am looking for 25.0002 (this value will then be converted to a string and then displayed).

Here is a simple little program that will allow you to round and format the way you wanted:
import java.text.*;
public class testFormat {
   public static void main(String[] args) {
      double x=25.00016000207654;
      x=Round(x,4);
      DecimalFormat NF=new DecimalFormat("0.####");
      String formatted=NF.format(x);
      System.out.println(formatted);
   public static double Round(double x, int dec) {
      double multiple=Math.pow(10,dec);
      return Math.round(x*multiple)/multiple;
}V.V.

Similar Messages

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

  • How to solve NaN error, while dealing with multiplication of double values

    i am getting NaN error in the program.
    consider this following code
    for (j=0;j<nh;j++)
    sum = 0.0;
    for (i=0;i<ni;i++){ sum = sum + (ai[i] * wi[i][j]) ;}
    //System.out.println(sum);
    ah[j] = sigmoid(sum);
    public static float sigmoid(float x)
    return ((Math.exp(x)- Math.exp(-x)) / (Math.exp(x)+Math.exp(-x)));
    ni = 2500-- no of input nodes;
    nh = 5000 -- no of hidden nodes;
    i am getting problem in calculating the "sum" value. its returning NaN for "sum".
    here a[i] values are around some +/- 0.XXXXXXXX upto 14 digits
    and wi[j][j] values are also +/- 0.XXXXXX upto 14 digits.
    all values are of datatype double.
    i was stucked up with this problem. what i am to do?
    give me suggestions..
    please reply me

    This can occur with double divisions. I wrote a small method that solves this:
         * Set double values that have a value of 'NaN' or 'Infinity' to 0.0. This can happen when dividing double values as they
         * don't cause a DivisionByZeroException.
         * @param value Double value to check.
         * @return Input value with 'NaN' and 'Infinity' set to 0.0.
        static public double resetNaN(final double value, final double resetValue) {
            return (Double.isNaN(value) || Double.isInfinite(value)) ? resetValue : value;
        }//resetNaN()

  • Convert a string to double with precision

    I am getting a value amount of say $45.00 from a jsp and set this value as a string for my other work. then i am changing this string to double by using this statement
    setAmount(Double.parseDouble(cstmt.getString(1)));
    my precision is lost when i get this amount it just shows 45.0 how can I get the precision of 45.00
    I would appreciate if any assistance is provided for the problem.
    thanks

    JSP's can use NumberFormat.
    However you should never use float/double to represent monetary values. Money has an absolute value (in terms of units used to purchase). Float and double do not (actually they do but they are in base 2 NOT base 10 like most money is). In most cases representation errors due to float and double do not really matter (if you have suitably analysed the usage of them) however people get very upset about errors when it comes to money
    matfud.

  • JSlider using double values instead of INT

    I need to create a slider that uses double values instead of ints...
    the default constructor is JSlider temp = new JSlider(JSlider.HORIZONTAL, int, int, int)....but i need to use
    JSlider temp = new JSlider(JSlider.HORIZONTAL, double,double,double)
    I want my slider to go from like 1.0 to 10.0 ....any ideas?
    thanks

    me has ritten a sample code fur ya... mite help...
    sorrie... not commented properly...
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JPanel {
         //Variable Declarations...
         JPanel valuesPanel;
         public JSlider slider;
         public JTextField midText;
         public JTextField lowText;
         public JTextField highText;
         int precision=1000;//to convert to double...(100-> 2decimal places, 1000->3decimal places.......)
         double lowLimit = 0;
         double midLimit = 5;
         double highLimit = 10;
         public Test() {
              initialize();
              addListeners();
              initComponents();
              addComponents();
         public void initialize() {
              valuesPanel = new JPanel();
              highText = new JTextField();
              midText = new JTextField();
              lowText = new JTextField();
              slider = new JSlider();
         public void addListeners() {
              addTextListenerTo( highText );
              addTextListenerTo( midText );
              addTextListenerTo( lowText );
              // if the slider is moved, the value of the mid will be updated in the testbox.
              // Sliders work on integers and not on double. so the limits are divided by precision to get a double number.
              slider.addChangeListener(
                   new ChangeListener() {
                        public void stateChanged( ChangeEvent e ) {
                             double n = ( double ) ( ( JSlider ) e.getSource() ).getValue();
                             midLimit = n / precision;
                             midText.setText( Double.toString( midLimit ) );
         * Sets different attributes and properties of the components
         public void initComponents() {
              highText.setText( Double.toString( highLimit ) );
              midText.setText( Double.toString( midLimit ) );
              lowText.setText( Double.toString( lowLimit ) );
              slider.setPaintTrack( true );
              slider.setPaintTicks( true );
              slider.setMinimum( ( int ) ( lowLimit * precision ) );
              slider.setValue( ( int ) ( lowLimit * precision ) );
              slider.setMaximum( ( int ) ( highLimit * precision ) );
         * Add all the components to the container (Panel).
         public void addComponents() {
              setLayout( new BorderLayout() );
              valuesPanel.setLayout( new GridLayout( 3, 3, 5, 5 ) );
              valuesPanel.add( new JLabel("Low") );          
              valuesPanel.add( highText );
              valuesPanel.add( new JLabel("Mid") );
              valuesPanel.add( midText );
              valuesPanel.add( new JLabel("High") );
              valuesPanel.add( lowText );
              add( valuesPanel, BorderLayout.CENTER);
              add( slider, BorderLayout.SOUTH);
         * Adds Focus and Action Listeners to the TextFields
         public void addTextListenerTo( JTextField textField ) {
              textField.addFocusListener(
                   new FocusAdapter() {
                        public void focusLost( FocusEvent evt ) {
                             updateLimits( ( JTextField ) evt.getSource() );
                        public void focusGained( FocusEvent evt ) {
                             String tempOldString = ( ( JTextField ) evt.getSource() ).getText();
              textField.addActionListener(
                   new ActionListener() {
                        public void actionPerformed( ActionEvent evt ) {
                             updateLimits( ( JTextField ) evt.getSource() );
         * This function is called when any action is performed on the text. It checks
         * if the value is valid and if not it displays a message. Also it updates the
         * slider value.
         *@param textField
         public void updateLimits( JTextField textField ) {
              double tempN = 0;
              try {
                   tempN = Double.parseDouble( textField.getText() );
                   if ( textField.equals( lowText ) ) {
                        lowLimit = tempN;
                        slider.setMinimum( ( int ) ( lowLimit * precision ) );
                   else if ( textField.equals( highText ) ) {
                        highLimit = tempN;
                        slider.setMaximum( ( int ) ( highLimit * precision ) );
                   else if ( textField.equals( midText ) ) {
                        midLimit = tempN;
                        slider.setValue( ( int ) ( midLimit * precision ) );
              } catch ( Exception ex ) {
                   JOptionPane.showMessageDialog( this, "Not a Number", "Error !!!", JOptionPane.WARNING_MESSAGE );
                   textField.setText( "0" );
         public static void main(String args[]) {
         JFrame f=new JFrame("test Frame");
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.getContentPane().add(new Test());
         f.pack();
         f.setVisible(true);

  • WPF Data gird double value in cell round up automatically

    Hi All,
      I have one datagrid where one of the columns contains double values. I placed limitations on length and decimal part. Decimal part is always comes with 2 digits. Now during editing the cell that holds double value in DataGrid , if I enter value of
    99.99 then it is becoming 100. At this moment the cell is still under edit mode.
     If the columns hold decimal type values then this automatic round up is not happening. But due to some constraints , at this moment we can't change the columns type from  double to decimal. So I just want to disable the auto round up with double
    values in DataGrid. I searched in MSDN forums but did not find any , tried adding StringFormat for columns. But it did not help.
    I tested by keeping the double value outside of the DataGrid ( in editbox ) , I don't see any automatic round up. So I suspect there could be something with DataGrid that is resulting automatic round up.
    Is there any way to disable this automatic round op on double values in DataGrid? I welcome your comment.
    Thanks,
    Brahmaji.

    Well, 99.99 as you mentioned in your original post is not the same value as 9999999999999999. You cannot store the value 9999999999999999 in a double field.
    You could change the type to decimal to be able to store values with a higher precision:
    public class Movie
    public string Title { get; set; }
    public int Year { get; set; }
    public string Director { get; set; }
    public bool Hit { get; set; }
    public decimal Price { get; set; }
    new Movie()
    Title = "The Lawnmower Man",
    Year = 1992,
    Director = "Brett Leonard",
    Hit = true,
    Price = 22.23M
    If you want to prevent the value of the source property from getting set when an invalid double value is entered you could implement your own ValidationRule:
    namespace SampleGrid
    class MyValidationRule : System.Windows.Controls.ValidationRule
    public override System.Windows.Controls.ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    string s = value.ToString();
    double d;
    if(double.TryParse(s, out d))
    return new System.Windows.Controls.ValidationResult(false, "invalid value");
    return System.Windows.Controls.ValidationResult.ValidResult;
    <DataGridTemplateColumn Header="Price">
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
    <TextBlock Text="{Binding Price, StringFormat=##.00}"/>
    </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate xmlns:local="clr-namespace:SampleGrid">
    <TextBox>
    <TextBox.Text>
    <Binding Path="Price" StringFormat="##.00">
    <Binding.ValidationRules>
    <local:MyValidationRule ValidationStep="RawProposedValue"/>
    </Binding.ValidationRules>
    </Binding>
    </TextBox.Text>
    </TextBox>
    </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    </DataGridTemplateColumn>
    <!--<DataGridTextColumn Header="Price"
    Binding="{Binding Price, StringFormat=##.00}" />-->
    Then the value won't get rounded. Of course you can still not set the double source property to 9999999999999999 though.
    There is no property that you can set on the DataGrid to prevent the value from getting rounded.
    Hope that helps. 
    Please remember to helpful posts as answer to close the thread and then start a new thread if you have a new question.

  • Unable to display double values in Excel sheet using JExcel API

    Hi
    I am writing code to generate report in the form of Excel Sheet using JExcel API.
    Everything is going fine but whenever I want to put some double values in a cell it is only showing 2 decimal places. My problem is "I want to show upto five decimal places".
    Any kind of reply might help me lot.
    Thank U.

    If you enable the submit zero option, it still happens? This is a new feature on the display tabl
    #NumericZero Enhancements
    To display a numeric zero in place of an error message, you can enter #NumericZero in any of the three Replacement text fields. When you use the #NumericZero option:
    · Excel formatting for the cell is retained.
    · All calculations with dependency on the cell will compute correctly and will take the value of this cell as zero.
    · This numeric zero is for display only. When you submit, the zero value is NOT submitted back to the data source.
    You cannot set display strings for cells that contain an invalid member or dimension name (metadata error). Metadata errors produce standard descriptive error messages.
    Errors are prioritized in the following order from highest to lowest. The error message for a higher-priority error takes precedence over that for a lower-priority error.
    1. (Highest) Metadata errors
    2. #No access
    3. #Invalid/Meaningless
    4. #No data\Missing

  • Error while setting Minimum value to  Input Number Spin Box..

    Hai
    I drag and drop a VO and created a table.In that table,i convert a column which contain an InputText field to Input Number Spin Box.At the time of page load ,the table fetches the datas from the DataBase and showing Number values in the SpinBox.After that,When i scroll the table through vertical scrollBar,the table showing *"fetching data"* and Error is throwing as *"The value must be Number"* .. In the VO,this attribute is Number.
    THIS ERROR ONLY OCCURS when i set the Minimum value of spinBox ..The purpose of setting minimum value is that i only want user to select ve value only..How can i restrict the user for selecting only ve values..?(ie,*How can i set minimum value to SpinBox?)*

    Try changing the datatype of your attribute in the EO to be Double instead of Number.

  • HOW to set the value attribute of FORM INPUT data to a variable in a JSP

    eg. Registration.jsp
    The data is accessed from an hidden field called course
    for example, if I have "Java programming" in the field course, and I use
    an expression to access the value from the hidden field.
    **My problem is that the data gets truncated to "Java" , I need "Java Programming"to display. The code looks like this
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <INPUT TYPE="text" SIZE=12 NAME="course"
    VALUE=<%=getParameter("course") %>
    IS there ANY OTHER WAY to set the value of VALUE to a variable?

    Instead of value=<%=request.getParameter("course")%>
    Use double codes
    value="<%=request.getParameter("course")%>"

  • Set default value for price unit when creating material master data

    HI: Every
    could you tell me how to use user-exit or else ways to set default value(such as 1000) for field "Price unit" (MBEW-PEINH) when creating material master data(MM01)?
    I have try to use Exit:EXIT_SAPLMGMU_001. However, this way cannot respones it.
    thanks
    Henry

    Hi: Ihave find out a solution
    Use BADI: BADI_MATERIAL_REF
    SPROlogistics general enhancement supplement or change default data (industry)
    And then creating a Implementation Name
    Double click method: CREATE_MATERIAL
    And then write code as below:
    method IF_EX_MATERIAL_REFERENCE~CREATE_MATERIAL.
              c_mbew-peinh = '1000' .
    endmethod.
    However, SAP still store '1000' in database evenif we change the default value such as 100 when we use TCode MM01.
    in additional, we still use MM02 to change the default value such as '100'
    can anybody tell me how to do?
    thanks
    Henry

  • Error adding double values

    Processing in my application requires adding huge double values,
    for instance i am adding 36561584400629760 and 1152062986011661
    and instead of getting 37713647386641421 I get 37713647386641424.
    Does somebody have a clue as to what the problem could be?
    I tried using BigInteger and primitive double datatypes.
    Thanks

    doubles precision is about 16 digits. Try this     BigDecimal bd1 = new BigDecimal("36561584400629760"),
                  bd2 = new BigDecimal("1152062986011661");
         System.out.println(bd1.add(bd2));
    or
         BigInteger bi1 = new BigInteger("36561584400629760"),
                  bi2 = new BigInteger("1152062986011661");
         System.out.println(bi1.add(bi2));

  • Query contains double value - seems cache problem

    Hi experts,
    in a Query (integrated planning) based on an Aggregationlevel based on a Multicube.
    The Multicube contains an Realtime InfoProvider to store planning data and a normal InfoProvider to show actual values.
    The load of actual values to the InfoProvider can be executed several times a month via ProcessChain -
    it´s a full load so the data loaded before will be deleted during the month in order to save the new monthly dataload.
    In the Query there were double values displayed for actual data after several loads during the month -
    but in the acutal InfoProvider only a single value is stored!
    It seems to be a buffer problem, since a deletion of all system buffers solves the problem - but this is not the way to handle the problem in productive area.
    How can the problem be solved?
    Setting of Planbufferquery of acutal data InfoProvider to not using Cache doesn't help.
    Thank you!
    Angie

    Hi,
    there is no data stored in acutal cube and the query column is restricted to actual cube.
    And actual cube only contains the value once, but the query can display the double value.
    If all buffers are reset, the query shows correct value - but this is not the way to handle the problem.
    What changes need to be made?
    Is there a setting in query cache or planningbuffer query cache or some other setting that can fix the problem?
    Best regards,
    Angie

  • Setting default values at the start of a process

    Hello
    I need to set some constant values to the attributes in data object as soon as start event of a process is triggered.
    How can I do that?
    Regards
    Vidyadhar

    Vidyadhar,
    Follow the below procedure to set Default Values
    1.Right Click on Start Event select Properties
    ->Goto Output Mapping Tab
    ->Double Click on Element on which you want to give Static Value
       and enter the value with double codes for eg: "Name"
    Make sure that this element value should be  has a Input to the next level.
    Thanks
    Srikanth

  • Pls Help :JTable Double Value Editing Problem

    hi friends
    as i am new to swings and Jtable pls help me if u can.
    in the code copied below when i start putting value into the Double column of JTable
    a ( .0 ) is appended at the end which is undesirable it should be like that only when the value is
    something like 22.99 and also i want to limit the double value's fractional part to be limited to 2 digits only.
    if this can be done in my Table model itself so that it will work everywhere i use this model
    Pls tell me what exactly do i need, a custom Cell Editor or Cell Renderer. and whether can i do it in the
    Table Model Defination class or whether i can only do it on the Jtable only.
    guys its so confusing.pls help
    if anyone can send a sample code for achieving this it would be of great help
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.text.*;
    public class TableProcessing extends JFrame implements TableModelListener
        JTable table;
        public TableProcessing()
            String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
            Object[][] data =
                {"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
                {"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
                {"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
                {"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            model.addTableModelListener( this );
            table = new JTable( model )
                //  Returning the Class of each column will allow different
                //  renderers to be used based on Class
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
                //  The Cost is not editable
                public boolean isCellEditable(int row, int column)
                    if (column == 3)
                        return false;
                    else
                        return true;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
         *  The cost is recalculated whenever the quantity or price is changed
        public void tableChanged(TableModelEvent e)
            if (e.getType() == TableModelEvent.UPDATE)
                int row = e.getFirstRow();
                int column = e.getColumn();
                if (column == 1 || column == 2)
                    int    quantity = ((Integer)table.getValueAt(row, 1)).intValue();
                    double price = ((Double)table.getValueAt(row, 2)).doubleValue();
                    Double value = new Double(quantity * price);
                    table.setValueAt(value, row, 3);
        public static void main(String[] args)
            TableProcessing frame = new TableProcessing();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }thank in advance
    jags

    No.
    But further to this try:
    public class MyCustomRenderer  extends javax.swing.table.DefaultTableCellRenderer
              private java.text.DecimalFormat FORMAT_DOUBLE;
              public MyCustomRenderer()
                      FORMAT_DOUBLE = new java.text.DecimalFormat("#, ##0.00");
              public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                        //NB! you could also set foreground/background here to indicate positive/negative values...
                        if(value.getClass().equals(Double.class))//is this a double?
                                double d = ((Double)value).doubleValue();
                                d = (Double.isNaN(d)||Double.isInfinity(d))?0:d;
                                this.setText(FORMAT_DOUBLE.format(d));
                        else//not a double so let's toString() it...
                               this.setText(""+value);
    }then, using code pasted above, specify a new instance of this class as the default renderer in your
    table.....
    :)

  • Data error - Double value of Sum row Aggregation

    Hello,
    I've recently created a new UNX universe based of SQL server query wich brings me determined values for payments and debts, when check the value on my XLS file wich is the main data source for the SQL DB, a single row is for 66,207.70 but on the universe when i check the values it doubles it.
    Here are four sets of pictures showing the value of a client PGE/ACRE when it's under AVG aggregation and when it's under SUM aggregation.
    Can someone help me identify the reason and how to fix it?

    Hi Marvin,
    In report level you getting double value so you can unchecked avoid duplicate row.
    Thank you
    Mustafa

Maybe you are looking for

  • Just updated to Mavericks and now I can't update apps using my Apple ID

    A few days ago I updated my 2012 Macbook Pro to Mavericks. Today I tried to update my apps but instead of asking for the password of my Apple ID, it asked for my dad's ID. The ID section was greyed out. The apps were all downloaded using my Apple ID.

  • Creating a fixed menu while the rest of the site scrolls

    I want to create a 2 column page where the left column is a menu and doesn't scroll, while the right side holds text/pictures and does scroll (no scroll bar needed, though).  An example can be seen here: http://hack.acmwsu.com/ Any ideas of how I can

  • Interlace Deinterlace Export and Youtube Problem

    We bought a nice new high end consumer camera - the Panasonic HC X900M . For the price of about $800 this little camera shoots sharp, crisp, colorful, high definition video. My son is spending a year in China and did not want a large camera. Anyway..

  • Cannot see Roles for my WebService

    I am trying to automate the following steps i do through WLS Console : a. In the Weblogic console's Home page, click on Deployments link form left, find "gateway-management-service" b. Expand, "gateway-management-service" and click on "GatewayManagem

  • QM Tables- Help Needed

    Hi all, I need to make a report on Defective Quantity ( Materialwise & Vendorwise). I am trying to make it using  the following tables... qave qals marc mkpf mseg qamb Can somebody suggest me from which table should get Defect type(code) & code group