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.

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

  • 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

  • Problems with convertNumber and Double values

    I've serious troubles using convertNumber with Double data in input fields.
    While output formatting works fine, the outputted string fails to be converted back - I get conversion errors.
    So the value that is written to the input field generates a conversion error being submitted! This is not good practice!
    I've found out the following: (I use german locale, so following examples containing ',' means decimal point)
    <f:convertNumber pattern="##0.00" />generates the right output, eg. for Double(20.50) - "20,50", but this value ("20,50") will not be parsed using the above pattern! Only values with non zero last minimum fractional digit (eg "20,51", "20,59", ... ) will be parsed!
    In addition, the above pattern doesn't parse numberstrings that don't contain all significant digits.
    For example an input of "20" will not be parsed to "20.00"!
    Maybe this is not the right forum for that problem, since i think this is a general java formatting problem (?).
    But as the problem arised by using the convertNumber tag and acting like this on numeric input fields is not very comfortable, I liked to post this here. Maybe someone can give me some advice?

    I also have found this problem, except that in my experience it is the decimal part that must be non-zero, not just the last digit of the decimal part. So with a pattern of "0.00" the string "1.50" (one and a half) will be accepted whereas the string "1.00" will not.
    My guess (just a guess) is that it is related to the documented behaviour of the DecimalFormat object when it parses a number. According to the documentation:
    The most economical subclass that can represent the number given by the string is chosen. Most integer values are returned as Long objects, no matter how they are written: "17" and "17.000" both parse to Long(17). Values that cannot fit into a Long are returned as Doubles. This includes values with a fractional part, infinite values, NaN, and the value -0.0. DecimalFormat does not decide whether to return a Double or a Long based on the presence of a decimal separator in the source string. Doing so would prevent integers that overflow the mantissa of a double, such as "10,000,000,000,000,000.00", from being parsed accurately. Currently, the only classes that parse returns are Long and Double, but callers should not rely on this. Callers may use the Number methods doubleValue, longValue, etc., to obtain the type they want.
    Which means that "1.50" will be returned as a Double while "1.00" will be returned as a Long. Perhaps there is then a class-cast exception whie trying to use this value?
    If this is indeed the problem, the solution is to use the getDouble() method of the parsed Number to create the Double to be returned, but this is for the implementer to do - not the user!

  • Confused with Calendars and TimeZones

    Hi, I'll explain what I want to do. I have a table with several of what I call a "Time Ranges". Each Time Range has a day (day of week), beginTime and endTime. I also have different clients, each from a different country. Each client has a timezone associated (the format of this timezone is not defined just yet, but it should be something like -3, -4, +1, etc).
    I want to get the current date, and be able to figure out if it is within a certain time range. For example, right now in Argentina is
    11:48 AM GMT-3
    This should match these time ranges:
    11:00~12:00 | -3
    10:00~11:00 | -4
    13:00~14:00 | -1
    And should not match this time range:
    11:00~12:00 | -4
    I'm trying to get the "current time for a certain time zone" with Calendar, and then be able to extract the time from that Calendar and compare it with my beginTime and endTime. I'm not getting anywhere.
    Something like this:
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-08:00"));
    System.out.println(cal.getTime());Is printing GMT-3 time. Please help.

    manugarciac wrote:
    Ok, I did it like this. The TimeRange Class has this method:
    public boolean isActive(String timezone) {
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timezone));
    if (cal.get(Calendar.DAY_OF_WEEK) == this.day) {
    Time time = new Time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 0);
    return (beginTime == null || time.after(beginTime)) && (endTime == null || time.before(endTime));
    return false;
    }Timezone should come in this format: "GMT-04:00" and Time is java.sql.Time.
    The only downside is that the Time constructor I used is deprecated. It says I should use the one that uses milliseconds since 1970. That kinda sucks, as I don't really care how much time passed since that time for this time. Any ideas of what I should use?forget java.sql.Time. use Calendar.set(int year, int month, int date, int hourOfDay, int minute) to set beginTime and endTime. use Calendar.compareTo(Calendar anotherCalendar) for the test.
    Edited by: pete_d on Sep 10, 2010 3:09 PM
    Not sure exactly what's going on in your TimeRange class but if the hour, minute, second and time zone in addition to the day of week (it seems that it does) for both begin and end time, then you can use this to create a Calendar instance to compare with the current time or to whatever other Calendar instance you want to check using its year, month day.

  • Possible bug: Saving array with extended and double precision to spreadshee​t

    If one concatenates a double precision array and an extended precision array with the "build array" vi and then saves using "Write to Spreadsheet File" vi any digits to the right of the decimal place are set to zero in the saved file. This happens regardless of the format signifier input (e.g. %.10f) to the  "Write to Spreadsheet File" vi.
    I am on Vista Ultimate 32 bit and labview 9.0
    This is a possible bug that is easily circumvented by converting to one type before combining arrar to a spreadsheet. Nonetheless, it is a bug and it cost me some time.
    Solved!
    Go to Solution.
    Attachments:
    Spreadsheet save bug.vi ‏9 KB

    Hi JL,
    no, it's not a bug - it's a feature
    Well, if you would look more closely you would recognize the "Save to Spreadsheet" as polymorphic VI. As this polymorphic VI doesn't support EXT numbers internally (it only supports DBL, I64 and String) LabVIEW chooses the instance with most accuracy: I64 (I64 has 64 bits precision, DBL only 53...). So your options are:
    - set the instance to use as DBL (by right-click and "Select type...")
    - make a copy of this VI, save it with a different name and make it support EXT numbers (don't rework the polymorphic VI as you would break compatibility with other LV installations or future revisions)
    And yes, those coercion dots always signal some conversions - you should atleast check what's going on there...
    Message Edited by GerdW on 05-21-2010 10:01 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Fundamental Confusion (about float and height) - please help

    hi. desired result is: a floated, fixed height and
    width div nested in another div with auto height and fixed width. but why does the mainbox div (see example) just collapse. am i missing a fundamental basic knowledge base here?
    <style type="text/css">
    #mainbox {width:300px; height:auto; background: #CCC}
    #mainbox .inside1 {width:100px; height:200px; float:left}</style>
    </head>
    <body>
    <div id="mainbox"><div class="inside1"></div></div>
    </body>
    </html>
    thanks.
    {Subject edited for clarity by moderator]

    mmm do divs not expand for floated content then?
    also, hans, i think you got the wrong thread.
    cheers

  • I'm trying to print Checks with Quicken. the print is 1/2 way across check with single and doubles

    My printer is the HP Laserjet 1102W When I load a single or double check into the manual feed vertically taken from a 81/2 x 11 sheet of checks Quicken prints so that only the date and amount show up in the middle of the check. I have used these checks for years with the manual feed on a Laserjet 4 Plus. How do I get the printing to move so that it covers the whole check?
    Howard Wexler

    Bobreba wrote:
    I am using Quicken Essentials 1.7.4 on a [Mac Pro, 2.8 Ghz Quad Core Intel Xeon with 16 Gb of memory], running 10.7.5.  I am in the process of upgrading everything to work on Yosemite and Quicken seems to be the most difficult problem to overcome.
    Thanks for your response and feedback.
    I would recommend you continue with Quicken Essentials.  As noted by others, it performs well on Yosemite.
    My personal experience is Quicken 2007 for Mac also on 10.7.5 (with many reports of it both updated and successfully running on Yosemite) and I personally would not touch Quicken Essentials with a 10 foot pole -- BUT, if it ain't broke for you, don't fix it!

  • Totally confused with iCloud and multiple devices

    Ok, So we have two each of the iPods, iPads and now iPhones.  Do we all share the same iCloud? Can we share apps through the cloud? How do I switch my iPad to the new one I got to give this one to my son. I am so new to all this apple stuff. Only been a few months and I'm still really confused.  What all goes to the iCloud? How do we see what's in the iCloud?  I really the the idiots instructions I think to figure this all out?  Can anyone help me?  How can I print from the iPad?  Everything I see says iOS 10 something?  I believe I only have 6 something? 

    Do we all share the same iCloud?
    icloud is designed so that only one user uses it to keep his/her devices in sync.  When multiple users use the same icloud account, they will then be sharing the same email address, contacts, calendars, notes, etc.  Usually that is not what two people want to do.
    Can we share apps through the cloud?
    You buy apps from the itunes store, that's different than icloud, and multiple users can use the same itunes account so that they can share apps, music, etc.  For a family, everyone usually uses the same Apple ID for an itunes account and individual Apple IDs for their icloud accounts.
    How do I switch my iPad to the new one I got to give this one to my son.
    What do you mean by "switch.. ipad to the new one"?
    What all goes to the iCloud?
    Backups of iOS devices, Apple services that you turn on to share data (settings>icloud; on an iOS device), third party apps that use icloud to sync their data between devices, email, photo stream, and more.
    How do we see what's in the iCloud? 
    Icloud is designed primarily for syncing data between the devices of the user - like getting all computers and devices to have the same contacts or calendars.  When you set up syncing (settings>icloud, turn on the services you want synced between your devices), some of that data will also be available to a computer's browser when you log into icloud.com.  Otherwise you view the data using the associated app, like the Calendar app to see events.  Other things that may be on icloud, like backups cannot be seen.  Also iCloud does not provide a photo gallary that others can view in a browser.
    How can I print from the iPad? 
    For that you need an "airprint" compatible printer. See,
    http://support.apple.com/kb/ht4356
    You can also print to a printer that's connected to a computer, but that computer needs special software, like Printopia for macs.
    Everything I see says iOS 10 something?  I believe I only have 6 something?
    There is no "10", version 6 is the current one.  You are probably thinking of OSX, whose versions are 10.x.y.  That's for macs, not iOS devices.

  • Two problems : areaChart along with Line and double y-axis in LineChart

    Hi Friends,
    This forum is very useful as we are getting lots of help from people who are trying out this new technology and giving/using help to/from others.I am developing a real time application in JavaFx in which I need to implement Charts using dynamic data coming from a server.
    Now I am facing two types of problem which may be interrelated in some way.
    Problem 1 :
    I need to combine an areachart along with a line Chart.There is nothing in JavaFx like area-line Chart so should i go with all area charts and make the fill-color of area series transparent(is it possible to have transparent fill in area-chart ? by css ?) OR i should stack two charts one area and one line on top of one another making the background of either transparent(once again is it possible to have transparent background for a chart so that background chart/series is visible ?) OR any other suggestion ? Anyways I tried stacking using stackPane and it turned out to be ugly combination of misaligned charts :-(
    Problem 2 :
    I need to put two y-axis(i.e secondary axis) on the same chart but i am unable to find such feature with my best efforts.I know I can set the side of Axis using setSide method of Axis class but how can i put it both side simultaneously.Also is there a way to put different scales on these axis ? I mean is it possible to have two different series with drastic difference in bounds(data range) to be put on same chart by attaching them to different Y-axis on the same chart ?

    I don't think there is anything in the JavaFX library which matches exactly what you need.
    You might be able to use some tips from the 3d pie chart I created at: https://gist.github.com/1485144. This demonstrates stacking multiple charts on top of each other, whilst removing rendundant details so it doesn't end up a jumbled mess and looking up items by their css tags and modifying them.
    There is now excellent documentation on chart css at http://docs.oracle.com/javafx/2.0/charts/css-styles.htm#CIHGIAGE. If this doesn't get you all of the css hooks you need to dig out the details required from the chart, then you can unpack jfxrt.jar and search for caspian.css or you can recursively print the nodes in the chart which will tell you the type and style of each node. Armed with this information you could should then be able to stack the two charts you created on top of each other, align them correctly and strip away the info you don't need. To get the second y axis to the other side of the chart you could look it up by css in code, then do a translateX on it to so that it is translated by a bind to the width of the x axis. Seems doable, if a little fiddly.
    You might be tempted to directly create an Axis yourself by creating an instance of http://docs.oracle.com/javafx/2.0/api/javafx/scene/chart/NumberAxis.html and laying it over your chart, but I was unable to get that to work (http://javafx-jira.kenai.com/browse/RT-18270) - even if you did so, you would have to manually set up the ranges and ticks as the chart library wouldn't handle that for you. Another way to create a Axis like thing is by creating a http://docs.oracle.com/javafx/2.0/api/javafx/scene/control/Slider.html, disabling user input on it and removing it's thumb via css.
    My efforts at answering chart questions in the past sometimes ended up as "That's not what I need": Re: How to create PieChart like this?
    Questions about charts are hard to answer without a link to an exact image of what the required chart is expected to look like.

  • Confusion with Membership and Billing

    I currently have Creative Cloud (Student and Teacher Edition) installed on my laptop for about a year now. I downloaded it through free subscription offered on a website, with a redemption code (thanks to an agreement between my college and Adobe.)
    For the last week or so, every time I turn on my laptop and open Photoshop the first time, I receive the following message: "We are having trouble verifying your membership. Either you're offline or there's a billing issue with your account. Please go online to manage your account and verify your billing information."
    I was in a slight panic, and scrambled around finding a way to renew my subscription, -- and I might have messed up in the process. First, I ordered Creative Cloud Student and Teacher Edition with a monthly billing plan with my MasterCard. But the next day, I ordered a new subscription with new redemption code. Now I have the following on my billing history:
    Even after all of these, I still have the same message concerning the status of my membership and billing.
    So, what should I do with my orders? Should I cancel my invoice?

    Cancel the paid subscription so you don't have a duplicate
    Cancel http://helpx.adobe.com/x-productkb/policy-pricing/return-cancel-or-change-order.html
    -or by telephone http://helpx.adobe.com/x-productkb/global/phone-support-orders.html
    As for the original problem, This is an open forum with a mix of program users and Adobe staff, not Adobe support... you need Adobe support
    Adobe contact information - http://helpx.adobe.com/contact.html may help
    -Select your product and what you need help with
    -Click on the blue box "Still need help? Contact us"

  • Confusion with Commit and Create Operations

    Hi:
    I'm using JDeveloper 10.1.3.4. I created an ADF Table that I want to use for data entry and modification. I also added Commit and Create operations as command buttons. Here's the behavior I'm seeing when I run the page:
    1. When I click on Create a blank record appears but no record is created in the database. This seems appropriate.
    2. When I enter data and click Commit, two records are created in the database: one with the data I entered and a blank record. This is problematic.
    Can anyone suggest a reason why I get 2 records during the Commit-button action? Also, is there a correct way to create this data-entry table?
    Thanks.

    Hello,
    Try using the createInsert operation instead of create.
    Both these operations only create a new row on the midtier, NOT in the database, which is intended.
    because adding the row right away to the database removed any use for the midtier in general
    cereate only creates a row in the midtier, it does not cimmit anything to the database and will not do so unless any value in that row is altered.
    createInsert create a row on the midtier and marks it so that the next commit will save this row to the database no matter if no values are changed.
    It doesnt explain why you got two records though, which is something different, maybe you clicked twice or called create twice?
    -Anton

  • Confused with saving and file sizes

    HI THERE. IM JUST A LITTLE CONFUSED ON HOW TO SEND MY FILES. I WANT A POSTER PRINTED THAT IS 196cm height // 143cm width. WHICH IS THE SIZE OF THE DOCUMENT I MADE ON PHOTOSHOP. HOWEVER IM CONFUSED ON SAVING THIS FILE AS ITS TOO LARGE APPARANTLY AND CANNOT BE SENT BY EMAIL. IVE FLATTENED THE IMAGE AND SAVED AS A JPEG BUT ITS STILL A HUGE FILE. COULD YOU TELL ME WHERE IM GOING WRONG?? IM SO CONFUSED.

    Most likely you increased the pixel count too high which inflated the file size required. An image that large is not viewed up close so you do not need to print it at a high resilution like 300Dpi.  Pring an image that size at 100Dpi will be fine.
    196cm x 143cm at 300dpi is 23150px by 16890px = 391,003,500px  391Mpixels
    196cm x 143cm at 200dpi is 15433px by 11260px = 173,775,580px  174Mpixels
    196cm x 143cm at 100dpi is   7717px by  5630px =   43,446,710px    43Mpixels
    Your camera pixels are most likely nearer to 43Mpixels then to 391Mpixel  intepolation can do just so much adding that many pixels will only produce a soft image anyway IMO

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

  • Confused with Windows and Parallels

    Dear all,
    Please can someone help?!
    I have a MacBook Air.
    I've been able to download Parallels onto my MacBook Air.
    But how do I get Windows to work via Parallels?  Do I have to do the bootcamp thing for Parallels to recognise it?
    A

    You have to buy Windows. Having done that, run Parallels and select the option to create a new guest OS. Follow the prompts.

Maybe you are looking for

  • Mavericks (inc. latest update today) - Apple Calendar  - Google calendar & phone (HTC One SV) - duplicates and disappearances...

    Hi. Since upgrading to Mavericks (inc. latest update today), a perfectly harmonious environment of Entourage > Apple Calendar > Gmail > Android phone has fallen apart. I understand that this is down to Apple removing local sync services in the Maveri

  • Problem in Software Upgrade download

    1. If I am doing Software upgrade for ipad mini, by the Update Button in iTunes Summary,      its downloading, but does not allow 'Pause' option. 2. If the download is happening, again in iTunes Summary I click Update Button, it starts another      d

  • How to post message (or Notify)  a frame?

    Hi I would like to know about how to notify a frame of some event? Say I would like to do the following. On clicking buttonA 1. disable some other buttonB. 2. Perform some lengthy operation in multiple other threads and post message saying operation

  • SLD is not accessible in our Netweaver Administrator

    Hi, Do u know why the SLD is not accessible in our SAP Netweaver Administrator? What steps should be taken to solve this problem? Please help. Thanks, Jennah

  • Query on CATT

    Hi all,   we know that CATT is used for testing purpose and also for mass upload of data by functional consultant.       can i know how many types of CATT are there and in which scenarios are they used?     how will we upload data using CATT.