Precision with float

i wana know how to display the value
5.1234
as
5.12
i wana know which package/class to use.
i checked with lang.Math and Math classes but i culd not understand which to use.
can somebody help me in this.
thanx

Hi
You can do the following:
String num = "5.1234";
//BigDecimal is A class in java.math
BigDecimal bDec = new BigDecimal(num);
//setScale sets the number of digits after the Decimal Point
// The Second argument tells the program whether to igonore the
// remaining digits or round them.
//See the API documentation for more information on these
bDec = bDec.setScale(2, BigDecimal.ROUND_UP);
//This should print out 5.12
System.out.println(bDec.toString());
Good Luck!
Eshwar Rao
Developer Technical Support
Sun microsystems inc
http://www.sun.com/developers/support

Similar Messages

  • Precision with float and double values

    Hi, does anyone knows how can i get more precise calculations with floating point numbers? Let's see an example:
    public class Teste {
    public static void main(String args[]) {
    float i = 0;
    while (i<=10) {
    System.out.println(i);
    i=i+0.1f;
    /* output
    0.0
    0.1
    0.2
    0.3
    0.4
    0.5
    0.6
    0.70000005
    0.8000001
    0.9000001
    1.0000001
    1.1000001
    1.2000002
    1.3000002
    1.4000002
    1.5000002
    1.6000003
    1.7000003
    1.8000003
    1.9000003
    2.0000002
    2.1000001
    2.2
    2.3
    2.3999999
    2.4999998
    2.5999997
    2.6999996
    2.7999995
    2.8999994
    2.9999993
    3.0999992
    3.199999
    3.299999
    3.399999
    3.4999988
    3.5999987
    3.6999986
    3.7999985
    3.8999984
    3.9999983
    4.0999985
    4.1999984
    4.2999983
    4.399998
    4.499998
    4.599998
    4.699998
    4.799998
    4.8999977
    4.9999976
    5.0999975
    5.1999974
    5.2999973
    5.399997
    5.499997
    5.599997
    5.699997
    5.799997
    5.8999968
    5.9999967
    6.0999966
    6.1999965
    6.2999964
    6.3999963
    6.499996
    6.599996
    6.699996
    6.799996
    6.899996
    6.9999957
    7.0999956
    7.1999955
    7.2999954
    7.3999953
    7.499995
    7.599995
    7.699995
    7.799995
    7.899995
    7.9999948
    8.099995
    8.199995
    8.299995
    8.399996
    8.499996
    8.599997
    8.699997
    8.799997
    8.899998
    8.999998
    9.099998
    9.199999
    9.299999
    9.4
    9.5
    9.6
    9.700001
    9.800001
    9.900002
    */

    http://forum.java.sun.com/thread.jsp?forum=31&thread=357174

  • Draw fct with float

    Does someone know why all draw fonction like drawArc, drawLine use int instead of float or double? it would not be more precise to draw with float or double?
    thx

    fonction? LOL!
    Seriously though, the method you want is java.awt.Graphics2D.draw(Shape) and fill(Shape). You would use it like this:
    protected void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;  // cast required to get Graphics2D functionality
      // Now make a shape, any shape
      Shape shape = new Rectangle2D.Double(2.5, 3.0, 30.0, 40.0);
      g2.setColor(Color.yellow);
      g2.fill(shape);
      g2.setColor(Color.black);
      g2.draw(shape);
    }Hope this helps.

  • TLF 2/2.1/3 Weird behavior with floating graphics?

    Hi guys,
    I'm working on a chat application running on RED5 / AS3 and I'm struggling to get my client "UI" working perfectly.
    My problem is related to the TL Framework, on every version available.
    Basicly, I want to display a picture ( for user messages ) and icons ( for notifications ) on the left side of my lines, like this :
    So, I'v been messing around with "float=start", "float=left" and such, but i'm always encountering weird behaviors whenever I scroll or resize my containerController. It's quite easy to reproduce with the following code :
    public class Main extends Sprite
              private var controller:ContainerController;
              public function Main():void
                        if (stage) init();
                        else addEventListener(Event.ADDED_TO_STAGE, init);
              private function init(e:Event = null):void
                        stage.scaleMode = StageScaleMode.NO_SCALE;
                        stage.align = StageAlign.TOP_LEFT;
                        removeEventListener(Event.ADDED_TO_STAGE, init);
                        var holder:Sprite = new Sprite();
                        addChild( holder );
                        var tFlow:TextFlow = new TextFlow();
                        for ( var i:int = 0; i < 50; i++ )
                             tFlow.addChild( createLine() );
                        controller = new ContainerController( holder, 400, stage.stageHeight  );
                        tFlow.flowComposer.addController( controller );
                        tFlow.flowComposer.updateAllControllers();
                        stage.addEventListener( Event.RESIZE, resizeController );
              private function resizeController( e:Event ):void
                        controller.setCompositionSize( 400, stage.stageHeight );
                        controller.textFlow.flowComposer.updateAllControllers();
              public function createLine( ):DivElement
                        var d:DivElement;
                        var p:ParagraphElement;
                        var im:InlineGraphicElement = new InlineGraphicElement();
                        im.source = new Bitmap( new BitmapData( 16, 16, true, 0x30FF0000 ) ); // 0x30 Alpha
                        im.float = "left";
                        d = new DivElement();
                        d.clearFloats = "both";
                        p = new ParagraphElement();
                        d.addChild( p );
                        p.addChild( im );
                        return d;
    Basicly, I'm stacking 50 transparent "floating" elements. It works fine most of time, but if I randomly resize my Flash Player Window, I can get the first "invisible" element to overlap the last "visible" :
    It seems to be happening right when the last "floating" element should disappear. Instead, it gets "over" the previous one. It happens upon container resize and scrolls. I'v encountered this issue on lastest 2, 2.1 and 3 TLF builds.
    Beside the visual "bug", it also screws up my container.getContentBounds().height calls - which can make scrolling "trembling", as the height gets reajusted.
    I'm running out of ideas about how to handle this. This bug appears whenever I use "floating" graphics and I can't think of any other way to display graphics on the left side of my chat-lines.
    Maybe someone ran into this very problem and figured out a way to make it work?
    Excuse my english, thanks in advance,
    Lionel.

    Thank you for your report. And I have found the root cause.
    In BaseCompose.as
    protected function composeFloat(elem:InlineGraphicElement, afterLine:Boolean):Boolean
    if (!floatFits && (_curParcel.fitAny || _curParcel.fitsInHeight(totalDepth, int(logicalFloatHeight))) && (!_curLine || _curLine.absoluteStart == floatPosition || afterLine))
                    floatFits = true;
    The condition of if is true, only when the weird behavior happens. We need to discuss about how to fix it.

  • Problem with Float - round down error

    I have to save in database (MySql) amount which is passed by user. For instance user writes 99999999999. But Float.parseFloat(request.getParameter("amoUnit")) returns value 9.9999998E10 . When I save this value in database I receive 99999998000.00. I want to have in database exactly what the user has written. Should I use differen data type? Thanks in advance.

    leonkaP wrote:
    ... I want to have in database exactly what the user has written. Should I use differen data type? Yes.
    If you want more precision than float, use double.
    If you want exact precision, use BigDecimal.

  • Smart Forms : problem with Float Variable

    Hi  Expert,
       I have a probelm with Float variable. In my smart forms one fields of table QAMV contain value like 8.0000000000000000E+01.
    I have to remove the exponent and display value like 80.
    I have tried wa_qamv-sollwert(E10.4).. but it not working.
    Can U suggest me some solution.
    Regards
    Swati.
    Edited by: Swati Namdev on Apr 27, 2010 12:19 PM

    Hi,
    Please follow the steps.
    1. In your smart form create a variable w_val ,, type,, associate type -->  CHAR10
    2. Now write a code, jsut above your node where u wud like to get this value... For this Create -> Flow Logic -> Program Lines.. Now you have editor..
    3. In input parameters , put i_tab-QAMV.. and in output parameter put w_val... and Code like below
    CALL FUNCTION 'MD_CONV_QUANTITY_FLOAT_TO_PACK'
      EXPORTING
        iv_menge       = i_tab-qamv
      IMPORTING
        EV_MENGE       = w_val.
    4. Now grag and drop this w_val from global data field list...your this w_val will have the rounded value.. Pls try this and check..   It will work.
    Regards,
    Lokesh.
    Edited by: Lokesh Tarey on Apr 27, 2010 9:28 AM

  • Draw line with float values possible

    Hi,
    Using Canvas drawing is possible to draw line with float values.
    graphics.drawLine(int,int,int,int);
    graphics.drawLine(float,float,float,float);Thanks and regards,
    Rakesh.

    not possible
    graphics.drawLine(float,float,float,float);...there's no such method in MIDP API: [click here for javadoc of Graphics class methods|http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Graphics.html#drawLine(int,%20int,%20int,%20int)]

  • JSlider with Floating point values

    I desperatly need to create a JSlider with floating/decimal values. For example between 0 and 1 and ticks within an interval of 0.1.
    The default behaviour of JSlider doesn't allow me to do so, hence is there any other way around ? I know it's possible to programmatically handle the required calculation by divding the values by 10, 100 or anything, but i want to display the actual values (floating/decimal) on the JSlider bar.
    Thanks in advance

    this might do you for the display
    import javax.swing.*;
    import java.awt.*;
    class JSliderLabels extends JFrame
      public JSliderLabels()
        setLocation(400,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JSlider slider = new JSlider(0, 100, 1);
        slider.setMajorTickSpacing(25);
        slider.setPaintTicks(true);
        java.util.Hashtable labelTable = new java.util.Hashtable();
        labelTable.put(new Integer(100), new JLabel("1.0"));
        labelTable.put(new Integer(75), new JLabel("0.75"));
        labelTable.put(new Integer(50), new JLabel("0.50"));
        labelTable.put(new Integer(25), new JLabel("0.25"));
        labelTable.put(new Integer(0), new JLabel("0.0"));
        slider.setLabelTable( labelTable );
        slider.setPaintLabels(true);
        JPanel jp = new JPanel();
        jp.add(slider);
        getContentPane().add(jp);
        pack();
      public static void main(String[] args){new JSliderLabels().setVisible(true);}
    }

  • How to creat N number of pulses precisely with PCTIO-10

    I need to send out N number of 1us pulses precisely with PCTIO-10. This is what I try to do: I use ctr1 to create 1us pulses. The output of Ctr-1 is counted by Ctr2 and the output of Ctr-2 in turn gates Ctr1. I use NI-DAQ CTR_PULSE function. I load N number of counts and Ctr2 enables Ctr-1, when ctr2 reaches the preloaded counts it toggles the output (pulse width =0) and holds ctr1. This suppose to do it. But the result is bad. It only works if the counting time of CTR-2 is greater than 180us, yet the PCTIO-10 has a time resolution of 140ns.
    Any ideas on what is going on or alternative methods?

    The PC-TIO-10 uses source frequencys of 1 MHz, except for Source 5 and Source 10, which use 5 MHz. In order to generate 1us pulses, you may need to use the 5 MHz source. Unfortunetly, since the PC-TIO-10 is an older counter board, there are not very many examples for how to program it using NI-DAQ.
    Also, you should be able to get a finite pulse train by using only 2 counters. You should Call CTR_Config for both counters, then call CTR_Rate and CTR_Square for the counter to generate the pulse train. You may want to check the parameters returned by CTR_Rate to make sure that they will give you the correct frequency and duty cycle. You should then call CTR_Pulse for the counter that will gate the pulse generating counter.
    I would suggest starting the program by generatin
    g a continous pulse train, making sure that works, and then adding the second counter to only generate N pulses.
    I hope this helps. If you have further questions, you may want to refer to the PC-TIO-10 User Manual and look at the Specifications for the AM9513 chip.
    Also, the following Knowledgebase talks about the maximum frequency possible for the PC-TIO-10:
    http://digital.ni.com/public.nsf/3efedde4322fef19862567740067f3cc/48a4924ba92f431c8625686900773e96?OpenDocument

  • Converting Vector with Floats to float[] typecast error?

    Java Developers,
    I am able to convert my String vector to a
    String[] but just can't get the Vector with Floats to be converted to a float[] array. I have looked into google and java.sun.com Forums but still cant seem to find the answer. I would really appreciate your help!
    This is how I am making the conversion from Vector(String) to String[]:
    legendLabelsArray = new String[columnHeads.size()];
    int k=0;
    Iterator e = columnHeads.iterator();
    while(e.hasNext()){
    System.out.println("inside the enumerator");
    legendLabelsArray[k] = e.next().toString();
    System.out.println("Array elements at " + k + " are " + legendLabelsArray[k]);
    System.out.println(k++);
    How can I make something similar to work with a Vector with Floats to float[] instead of Strings?
    Thanks,
    Musaddiq
    [email protected]

    Something like this ...
    float[] floatArray = new float[vectorOfFloats.size()];
    int k=0;
    Iterator e = vectorOfFloats.iterator();
    while(e.hasNext()){
    floatArray[k] = ((Float) e.next()).floatValue();
    k++;

  • Precision problem with float

    Hi,
    I have class with an amount variable whose type is float. If a value like 999999.99 is set to this variable, when I try to display this in JSP, the precision is lost. It displays 1000000. But my requirement is to print 999999.99. Is there any to solve this problem? The constraint to this prioblem is I can't change the data type of this variable. (Actually this class is generated through Castor. The xsd type is float. I am not supposed to change the XSD).
    Please advise.

    There's nothing to be done about it if you can't change the data type. See for yourself:    System.out.println(999999.99F == 1000000F);  // yep, they are equalBlame the person who decided that you should use float.

  • Polygons with float precision?

    Is it possible to use polygons with arrays of floats? I've looked up the source code and it seems that the code is all based around the use of ints.
    How would I go about making a polygon use floats so that it can move smoothly around the screen? I've got it moving using ints, but this causes horrible jerky-like movement.
    Thanks
    Ribot.

    g2d.drawOval(circleX, 400, 25, 25);
    circleX++;That should move it by 1 pixel on the x axis each time through the loop, unless you have other code that is changing the value (perhaps you could add System.out.println("CircleX = " + circleX) statements before your drawOval statement...
    in the same animation loop I feature the following
    code which moves the graphics2D object by fractional
    amounts across the screen (this is the effect I want
    to get with a polygon based shape):It only moves on screen when the value of the integer part of the fraction changes (your monitor would be unable to move it by a fraction of a pixel). Why not use double values and cast them to ints if you want to replicate this?
    >
    circle.setFrame(550.5+(tickerTest*0.1), 300.5, 50,
    60);
    Area test = new Area(circle);
    g2d.setColor(Color.magenta);
    g2d.fill(test);
    tickerTest++;
    Is there a Graphics2D polygon type object? I've
    looked in the API and haven't found anything. how about g2d.drawPolygon()
    I have done this without double buffering and it works perfectly... a 20ms delay and there isn't any flicker (P3 600MHz, JDK 1.2.2), so I really don't understand unless you have some massive processing running concurrently... javax.swing.JFrame frame = new javax.swing.JFrame();
    frame.setSize(200,200);
    frame.show();
    java.awt.Graphics2D g2d = (java.awt.Graphics2D)frame.getGraphics();
    int x = 50;
    int y = 50;
    int dx = 1;
    int dy = 2;
    int width = 20;
    int height = 20;
    for(int i = 0; i < 1000; i++) {
         g2d.clearRect(0, 0, 200, 200);
         g2d.drawOval(x, y, width, height);
         x += dx;
         y += dy;
         if(x < 0 || x > 180) dx *= -1;
         if(y < 20 || y > 180) dy *= -1;
         Thread.sleep(20);

  • Problem with floating point precision

    Hello!
    I need to store in a variable a number like this 1234512345.123412345.
    But when I store it on a double or long double... it gets truncated to 1234512345.123412... only six decimals?
    What can I do??
    Thanks!

    If you are going to use the BigDecimal class, it is worth bearing in mind a tip that was passed on to me from georgemc. If you create the BigDecimal class instances using the constructor that accepts a String as input, then you can easily specify how many digits should follow the decimal point.

  • Lost Data Precision with msync_com.dll

    Hi,
    I develop a program in C#. With Oracle Lite 9, the data precision of tables were good when I msync inside my program (i dont use msync.exe, I call functions of msync_com.dll), but now we have migrated in Oracle 10g et we loose data precision. For example, a field which contains "19,60" becomes "19" after syncing.
    I use msync_com.dll and I don't know which options I do use to force the data precision...
    Is anyone has meet this problem ?? When I use msync.exe, the precision is good, I get float... but not with my program and msync_com.dll of oracle lite 10g, I loose this precision, float become int !! weird...
    Thanks a lot for your help.

    Hi,
    All you need for Oracle Lite connections is in the Oracle.Data.Lite.dll. You would create a database connection object and connect that way.
    See the tutorial here: http://otn.oracle.com/products/lite/tutorials/index.html
    Good Luck

  • Precision operation (Float point) on FPGA 2011

    Dear Experts....
    For my application I have to perform demodulation operation on FPGA. I want to store an array of double precision number. When I am trying to perform any double precision number operation I am getting this error "Wire:Type not supported in current target" From forums I came to know that on FPGA  in Labview 2011 I cannot have double precision operation. What is alternative?? Please help me with this. Due to this issue my work has been delayed due to this problem..
    Thanks... Kindly guide...
    Solved!
    Go to Solution.

    Dear Mathan, thanks for your reply.... I have already gone throught the link you sent, but for my application I have to have array of floating points number. I can not have integer numbers. Here I have attached my vi. I have to mix a signal of 20 Mhz with sin and cos signal to achieve demodulation. So for Sin and Cos values I have to have floating point. Is ther any way to overcome this problem?
    Attachments:
    fpga.vi ‏30 KB

Maybe you are looking for

  • "Files can not write or be written to disk" (pic problem)

    I can't seem to figure out why I get the error that I can't write to the disk. Does that mean I can't write to the ipod? I've tried 5 r's and still can't figure it out. Is is an OS issue on my comp? Anyway, I can't figure it out...thanks for your tim

  • Virus preventing users from logging in?

    Over the weekend our anti-virus began sending out alerts about blocked web traffic, This morning when I came in I looked at the computer, when I got to his desk the user was trying and failing to login. Having locked out his account with so many fail

  • Contact Sheet??

    Using Photoshop CS5, I can't figure out how to make a contact sheet with a bunch of photo's.

  • Count of all ebeln for each SUBMI

    hi all, i want to Get count of all EBELN for each SUBMI. Get EBELN & EBELP from EKPO table. Get ANFNR from EKPO for the EBELN & pass it in EKKO-EBELN Get SUBMI from table EKKO for ANFNR = EBELN Pass the above SUBMI in table EKKO & get all EBELN Get c

  • Cannot install latest version of flash...sliprt.dll is missing (error)

    I am trying to install the latest version of flash into my Windows 7 OS but when I hit install I get a message saying that the file sliptr.dll is missing. I thought it might have been CCleaner causing problems with registry cleanup but I have re-inst