Float and Double - 5.1 divide by 3.0

Hi everyone,
I am quite new to java programming in term of using it. I wrote a test class to learn about float and double. However when I wrote the below code, I got a strange result. So, I wonder if java's float and double have any kind of exception I should be aware of. This won't happen if I just change from 3 to other numbers. Any suggestion? Thanks in advance.
public class MathTest {
public static void main (String args[]) {
float f1 = 5.1F;
float f2 = 3.0F;
double d1 = 5.1;
double d2 = 3.0;
System.out.println("Float result : " + f1/f2);
System.out.println("Double result : " + d1/d2);
Result:
Float result : 1.6999999
Double result : 1.7

This is due to the way that binary numbers convert to digital numbers and is expected. See these threads for explanations:
http://onesearch.sun.com/search/onesearch/index.jsp?qt=%2Bprecision+%2Bwrong+double&col=developer-forums&rf=0&chooseCat=allJava&subCat=siteid%3Ajava

Similar Messages

  • Confused with float and double

    Hi,
    I have done the following program which is supposed to deal with temperature and scales.
    import java.math.BigDecimal;
    public class Temperature {
         private float temp;
         private char scale;
         public static void main(String args[]) {
              Temperature t = new Temperature(40.5, 'F');
              System.out.println(t.getCTemperature());
         public Temperature() {
              temp = 0;
              scale = 'C';
         public Temperature(float pTemp) {
              temp = pTemp;
              scale = 'C';
         public Temperature(char pScale) {
              temp = 0;
              scale = 'C';
         public Temperature(float pTemp, char pScale) {
              temp = pTemp;
              scale = pScale;
         public float getCTemperature() {
              if (scale == 'C') {
                   return temp;
              } else {
                   float celciusTemp = 5 * (temp - 32) / 9;
                   BigDecimal bd = new BigDecimal(celciusTemp);
                   return bd.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
    }When I try to compile I get the following error :
    F:\programs\ch4>javac Temperature.java
    Temperature.java:8: cannot find symbol
    symbol  : constructor Temperature(double,char)
    location: class Temperature
    Temperature t = new Temperature(40.5, 'F');
    *^*
    *1 error*
    I don't understand why the number 40.5 is considered like a double and that I can't use Temperature(float, char);
    If I'm not mistaken the compiler is asking for a constructor like Temperature(double, char) right ??
    thanks.

    Can I second Mr TuringPest, and Sir J.Bloch... Do NOT use floats, unless of course you have a really really good reason. Internally, java does all it's floating point arithmetic in doubles anyways, so you're just shooting yourself in the accuracy-foot by forcing it to: promote to double to calculate, "narrow" result back to float... promote, narrow ... promote, narrow ... promote, narrow ... The net result can be astoundingly inaccurate... So just use doubles.

  • Method's choose: Float and double Why ? pls!

    void testDoit()
              float f = 3.14f;
              doIt(f);
         void doIt(Float f)
              System.out.println("Float");
         void doIt(double f)
              System.out.println("double");
    why "double" is the ouput in the previous example!

    hummm
    thanks man!
    Really, acording the "Java primitives data types"
    a float (32 bits) is a double ( 64 bits ) !
    mathematically
    double contains float!
    then, before a cast be executed...the second method is choosen
    Thank you!
    ;)

  • 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

  • What is the match of float or double data type in abap?

    I have tried p, but I could not handle decimal numbers such as 10.6 or 10,6(no matter which one is preferred, the question is the same...).
    How can I handle these numbers?
    Thanks.

    Hi
    Hope you know about FLOAT and Double.But you can use the same P for handling decimal places...
    Use like this.
    Data :Deci type P DECIMALS 2.
    Get bckif you are getting error still...
    Reward All Helpfull answers..........

  • How to format floats (or doubles ) but not converting to String?

    Hi everybody,
    my question is simple:
    I have a number,lets say 51,4567321 and i want to format it ,as a float or double ,as 51,45.
    One way is to do:
    float x=((hits * (float) 100) / this.getAccesses());
    DecimalFormat perCentFormatter = new DecimalFormat("00.00");
    String formattedNum=this.perCentFormatter.format(x);and that will create a string "51,45".
    But how do i do to create a float or double or anything else that holds the value with 2 decimal points after mantissa?e.g XX,XX
    Thank you very much,
    Chris

    A few options:
    1) just live with it. The float and double formats hold their values in binary, you know, and you only have approximations of multiples of tenth and one-hundreds of unity. It's all just approximations for those types. C'est la vie.
    2) Use java.math.BigDecimal, which gives you control over rounding.
    3) Change your design, so you use integers with the lower unit. So if the float currently "51,23" represents 51 Euros and 23 cents (what's the word? Europennies?), then you'd use an int of 5123 to represent five thousand one hundred and twenty-three cents.

  • Formatting a string with time stamp and double precision numbers

    %s\t%f\r%f
    This is a format string that I have in old code that I've decided to change.  Problem is I cannot make sense of the string codes in my own old code! Let me explain what I want, and hopefully someone can explain how to do it.
    I am using the format into string subvi to merge a time stamp (formatted as %m%d%Y%H%M%S%5u) and two different double precision numbers.  This string is then wired into the Write Characters to File subvi so that I can record data as a .txt file, and open it in either Matlab or Excel.  There is a minor problem with the string format above because in excel the first time stamp entry is blank, and the first loop only gives the two double precision numbers withouth the time stamp - the time stamp appears in the next loop (probably a looping issue and not due to the string format, but if you see differently please let me know).  Now what I want to do is 1. potentially fix that problem and 2. add some more doubles. 
    1. Is there a string format issue that is evident that I am not seeing that causes the time stamp to be formatted into the string after a carriage return?  Or should I be looking at looping issues?
    2. How do I add another one - three floating point numbers (double precision)?  Are the \'s marking different numbers in this string constant?  Or is it the %?  I can't find any information about the \'s, but I see that % begins the format specifier. 
    Ideally, I want these data in the following columns:  Date, Time(absolute), FP, FP, FP, carriage return for the next loop (FP is floating point double precision number).
    Thanks,
    Brad

    Hi JonN,
    Here there is no need of string concordinate function (in your code), the same result you can find if you connect the output of the format string to shift register, and shift register in data to initialize string connector in format into string function.
    <<KUDOS ARE WELCOME>>
    ELECTRO SAM
    For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life.
    - John 3:16

  • Dimensions - int and double mixed?

    Dimension x = new Dimension(int_1, int_2);
    int height = x.height;
    int width  = x.width;
    double height_d = x.getHeight();
    double width_d = x.getWidth();When you create a dimension you give it to integers as the width and height. However, if you call getHeight() or getWidth() it returns double-precision values. What's the point? Why does it use int/doubles?
    Thanks

    The methods getWidth/getHeight are inherited from RectangularShape.
    We have:
    Rectangle2D extends RectangularShape
    Rectagle extends Rectangle2D //implemeted with ints
    Rectangle2D .Float extends Rectangle2D //implemeted with floats
    Rectangle2D .Double extends Rectangle2D //implemeted with double
    So the implementations are providing the precision. Since the getWidth/getHeight methods are common
    to the hierarchy they return doubles to avoid loss of precision in the Rectangle2D .Double case.
    On the other hand, if I'm working with a java.awt.Rectangle I just access the public width and height fields
    directly.

  • Validating a JTextField having a float or double value.

    Hello,
    I need help in validating a JTextfield which will accept a float or double value because it the deposit field and it shouldn't be of length more than 7 before the decimal and 2 after the decimal.That is it should be of length 10.I have written the following code for the validation.
    txtDeposit.addKeyListener(new KeyAdapter(){
    //Accept only integer value
              public void keyTyped(KeyEvent e){
              char c = e.getKeyChar();
    if((txtDeposit.getText()).length() == 10)
              if (!(Character.isDigit(c)))
              if(!Character.isISOControl(c))
              getToolkit().beep();
              e.consume();
              });//end of txtDeposit*/
    Please help.

    use javax.swing.InputVerifier
    import java.awt.BorderLayout;
    import java.awt.Toolkit;
    import javax.swing.InputVerifier;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class VerifyInput extends JFrame {
        public VerifyInput(){
            super("Input Verifier");
            this.setSize(200, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextField txt = new JTextField();
            txt.setInputVerifier(new CheckInput());
            this.getContentPane().add(txt, BorderLayout.NORTH);
            JButton btnMoveFocus = new JButton("CLick");
            this.getContentPane().add(btnMoveFocus, BorderLayout.SOUTH);
        public static void main(String[] args) {
            VerifyInput f = new VerifyInput();
            f.setVisible(true);
        class CheckInput extends InputVerifier{
            private int lengthBeforeDot = 7;
            private int lengthAfterDot = 2;
            public CheckInput(){
            public CheckInput(int lengthBeforeDot, int lengthAfterDot){
                this.lengthAfterDot = lengthAfterDot;
                this.lengthBeforeDot = lengthBeforeDot;
            public boolean verify(JComponent input) {
                boolean correct = true;
                try {
                    JTextField tField = (JTextField) input;
                    String text = tField.getText();
                    if(text.length() == 0){
                        return true;
                    if ((correct = isDoubleOrFloat(text))) {
                        correct = isFormatCorrect(text);
                } finally {               
                    if(!correct){
                        Toolkit.getDefaultToolkit().beep();
                        System.out.println("Not Correct");
                    }else{
                        System.out.println("Correct");
                return correct;
            private boolean isDoubleOrFloat(String text){
                try{
                    Double.parseDouble(text);
                }catch(NumberFormatException nfe){
                    return false;
                return true;
            private boolean isFormatCorrect(String text){
                int dotIndex = text.indexOf('.');
                if(dotIndex < 0){
                    return text.length() <= lengthBeforeDot;
                String beforeDecimal = text.substring(0, dotIndex - 1);
                if(beforeDecimal.length() >= lengthBeforeDot){
                    return false;
                String afterDecimal = text.substring(dotIndex + 1);
                if(afterDecimal.length() > lengthAfterDot){
                    return false;
                return true;
    }

  • With Mavericks I have to hold command key down and double click to get a sub folder to open in a new window.  Can I go back to just double clicking ?

    With Mavericks I have to hold command key down and double click to get a sub folder to open in a new window.  Can I go back to just double clicking ?

    Of course. To do it, open a Finder window, go to Finder menu (on the menu bar) > Preferences > General, and untick "Open folders in tabs instead of new windows".

  • Outlook 2010 apostrophe, single and double quotes are changes to question mark while sending mails to other internet receipient.

    We are using MS Outlook 2010 as our mail client. But we have noticed that whenevr we sent a mail to any other internet mail recipient all the "apostrophe", "single" and "double quotes" have automatically converted to ?. We have
    done almost all the workaround found in this site such as
    1.New a message and focus on the message window > click File > Options > Mail > Spelling and Autocorrect… > Proofing > AutoCorrect Options… > AutoFormat > clear the box before “Straight quotes” with “smart quotes”
    2. Used different encoding. We presently using US-ASCII for outgoing message. etc.
    Need your help to sort out these issues urgently.
    Waiting for a solution.

    Hi,
    What is your account type? IMAP, POP or Exchange?
    Send an email from the webmail, ask the recipient if this issue persists.
    As far as I know, this problem is always related to the encoding for outgoing messages, and here I suggest you try UTF-8:
    Go to File -> Options -> Advanced -> International options -> Uncheck "Automatically select encoding for outgoing messages", then select "Unicode (UTF-8)" beside "Preferred encoding for outgoing messages" -> OK.
    Hope this helps.
    Regards,
    Melon Chen
    TechNet Community Support

  • No DNS and Double NAT

    Hello, I've recently encountered a very frustrating bug in my system that I could use some help troubleshooting.  I've read several similar posts, some are resolved while others are not, however none of the resolutions have worked for my situation.  Here it goes:
    I have an old macbook pro, a new macbook air, a white macbook and 2 iPhone 4s's all connected to the internet via WiFi through an AirPort Extreme.  The AE is connected to a cable modem which has internet service through Cablevision in NY.  There is also an AT&T Microcell hooked up to the AE to boost my cell signal.   All of this equipment has been working flawlessly together for a long time.  Until recently.  It could have started after an update, there have been several lately on all of the equipment including the firmware in the AE.  Anyway, I'll be connected without any issues - all lights green and happy - when suddenly, the internet will drop off and the AirPort Utility will pop up and warn me that:
    1) On the "internet" icon, it will say "disconnected"  
    2) On the AE icon, it says "No DNS server and Double NAT"
    After a few minutes and nothing done on my part, the lights turn green, the internet reconnects and all is well again. 
    This happens frequently and is really beaching a nuisance.  Due to the frequency of the disconnection, I can no longer download a large file, update, or anything.  Streaming video is impossible.
    So far, I have tried bridge mode and cycled the power in the order recommended to no avail.  When I do that, the AE turns green, but the internet says "not connected".  I have also read that there might be too many IP addresses which is not sitting well with my ISP, so I disconnected everything including unplugging the Microcell.  Lastly, there are no other wireless phones or devises in the house.  All to no avail.
    I should also mention that this began occurring on my Time Capsule, which I replaced with the AE in an attempt to fix this issue. 
    Any help would be greatly appreciated.
    Joe

    Sounds very similar to what I've been trouble shooting for 2 months now, only I have DSL from AT&T and I don't see the Double NAT warning.  My last post on the problem is here. 
    My only emergency solution for getting by day to day on the internet is to unplug the AE and connect one Mac directly to the DSL modem.  There's no shared connection or WiFi.  I looked at hosting WiFi from the Mac, but the only security available with that is WEP which isn't considered secure.  Even with this set up, I think (seat of the pants) that there are quality of service problems. 
    I've replaced the Airport Extreme with 2 different new units and the DSL modem with a new unit to no avail.  The Genius Bar and Apple phone support couldn't solve this, nor have 2 calls to AT&T support and one visit from an AT&T repairman.
    I would like to know how to better test or quantify the poor quality of connection that seems to be the problem.

  • TS1843 I am getting the following error messages- No DNS Server and Double SAT.  Can anyone walk me through a fix?

    Airport Express- No internet connection. I am getting the following error messages- No DNS Server and Double SAT.  Can anyone walk me through a fix

    Try putting these numbers in Network>TCP/IP>DNS Servers, for the Interface you connect with...
    208.67.222.222
    208.67.220.220
    Then Apply. For 10.5/10.6 Network, highlight Interface>Advanced button>DNS tab>little + icon.
    Might also put them in the Airport Express, no idea what Double SAT is!?

  • I have upgraded to an Iphone 6 and am at IOS 8.2.  My calendar alerts no longer show up as notifications on my phone.  I have gone into settings and double checked that notifications for calendar was on and it is. Any ideas on a fix?

    I have upgraded to an Iphone 6 and am at IOS 8.2.  My calendar alerts no longer show up as notifications on my phone.  I have gone into settings and double checked that notifications for calendar was on and it is. Any ideas on a fix?

    I have iPhone 4s but the same problem with calendar on 8.2 iOS - no sound, no notification appears - but everything is switched on.

  • Converting from String to float and vice versa

    I'm interested in people's thoughts on where common logic to convert between various field types should be stored in an application to minimise code duplication and maintenance.
    I have an application which consists of an object and a jPanel which displays and maintains this object. The object contains a number of private float fields which are accessed by getters and setters. The jPanel contains one jTextField for each of the fields within the object.
    Currently I have numerous lines of code in the jPanel to convert between the values needed by the getters and setters in the object (i.e. float) and the String value used by the jTextFields. This code handles cases where the String value may be blank or null.
    I've thought that one alternative to having all this conversion/validation code in the jPanel is to create a second set of getters and setters for each field which accept and return String values.
    What do people think about this? Is it advisable for only have one getter and setter for a variable? Should I put the conversion/validation logic for each field into a seperate common routine?
    Thanks,
    James.

    Hi James,
    You should go with whatever works best for you. By creating multiple getters and setter you save yourself from repeating the same code throughout your program.

Maybe you are looking for