Calculations with floating numbers

I am doing some calculations within an application have have found the following happens:
System.out.println("calculation: " + (22.0*4.4));
results in the output:
calculation: 96.80000000000001
Why is this? I understand that rounding has to happen on sum figures, but not these two - how can I get the 'proper' result of 96.8??
Thanks

import java.math.BigDecimal;
public class Test {
    public static void main(String[] args) {
        double d1 = 22.0;
        double d2 = 4.4;
        System.out.println(d1);
        System.out.println(d2);
        // with Java 5.0 printf
        System.out.printf("%.1f%n", d1 * d2);
        // With BigDecimal
        BigDecimal bd1 = new BigDecimal(d1);
        BigDecimal bd2 = new BigDecimal(d2);
        System.out.println(bd1);
        System.out.println(bd2);
        BigDecimal product = bd1.multiply(bd2);
        BigDecimal scaled = product.setScale(1, BigDecimal.ROUND_HALF_UP);
        System.out.println(scaled);
}Cheers, Neil

Similar Messages

  • Calculator with two numbers

    Dear Forum
    Im working a calculator with a textfield. It can calculate a if a enter only one number, but when i try to enter two or three doesnt work. I have test several codes but they are not working at all. Could any someone give me a hand. Please se te attach file.
    var numeroEntrado = "";
    var campoUno:int = 125;
    var campoDos:int = 20;
    var elResultado1 = 0;
    var elResultado2 = 0;
    proteinas.text = "125 grs.";
    colesterol.text = "20 mml.";
    colesterol.backgroundColor = 0x9999FF;
    textoColesterol.backgroundColor = 0x9999FF;
    numeroPorciones.maxChars = 3;
    numeroPorciones.restrict = "0-9";
    btn.addEventListener(MouseEvent.MOUSE_UP, suma);
    function sienteTecla(event:KeyboardEvent):void {
        if (event.keyCode == 48) { numeroEntrado = 0; }
        if (event.keyCode == 49) { numeroEntrado = 1; }
        if (event.keyCode == 50) { numeroEntrado = 2; }
        if (event.keyCode == 51) { numeroEntrado = 3; }   
    function suma(evt:MouseEvent):void{
            proteinas.text = "";
            elResultado1 = Number(campoUno) * Number(numeroEntrado);
            proteinas.text = elResultado1 + " grs"; 
            colesterol.text = "";
            elResultado2 = Number(campoDos) * Number(numeroEntrado);
            colesterol.text = elResultado2 + " mml" ;
            numeroPorciones.text = ""
    thanks
    IN

    It's difficult to say without understanding your intent.
    I don't see where you event listener for sienteTecla  is being assigned.
    If numeroEntrado is supposed to be numeroPorciones value (a guess) then perhaps you could just do something like this:
    function suma(evt:MouseEvent):void{
        if (numeroPorciones.text!="") {
            proteinas.text = "";
            elResultado1 = Number(campoUno) * Number(numeroPorciones.text);
            proteinas.text = elResultado1 + " grs";
            colesterol.text = "";
            elResultado2 = Number(campoDos) * Number(numeroPorciones.text);
            colesterol.text = elResultado2 + " mml" ;
            numeroPorciones.text = ""

  • Calculating with float...

    Hi, how can I manage the following calculation, without external librarys.
    A = X / (Z / Y)
    A, X, Z, Y are all short, but the 2 results shouldn be rounded...is it possible in java me to calculate something like this ?
    ...mhh...Im sorry for this newbish question, maybe its quite simple, but Im wonder about..

    No, you cannot do this without external libs in CLDC 1.0. floating point is not supported.
    You might scale all numbers factor 10 or 100 and then do the division. It will give you more accuracy.

  • Calculations with Rounded Numbers

    I've created a form in Adobe X that has a few calculated fields.  For ease of conversation, we'll call them Field A, Field B and Field C (see below).  I need Fields A and B to be rounded to the nearest whole number so that Field C is also a whole number.  I've tried formatting Fields A and B to show no decimals but the calculaton is still being performed on the non-rounded numbers.  Can anyone help with this?  Thanks.
    Field A - Field B = Field C

    George I must be missing something.  I added the math.round functions as shown in your example but now it doesn't calculate at all.  Can you look at the coding shown below and let me know where I went wrong?  Thanks.
    Updated Coding:
    (function(){
    var totalMiles = math.round(+this.getField("Total Miles DrivenRow1").value);
    var homeMiles = math.round(+this.getField("Home Base MilesRow1").value);
    var diff = totalMiles - homeMiles;
    if (diff<0) diff = 0;
    event.value = diff;})();
    Original Coding:
    var totalMiles = +this.getField("Total Miles DrivenRow1").value;
    var homeMiles = +this.getField("Home Base MilesRow1").value;
    var diff = totalMiles - homeMiles;
    if (diff<0) diff = 0;
    event.value = diff;

  • Access db: problem with float numbers if access isn't installed

    hi all,
    i wrote a simple application to store/retrieve float values into/from an access db.
    i tried it on my computer (with ms access installed) and i could store float values (ie 136.5), but when i tried my application (copying all classes and the db) on another machine without ms-access, i couldn't store float values, only int (ie 1365.0).
    the column "price" in the db is set as float with 1 decimal number, and there are other columns set as string, with no problem.
    anyone could help me?
    should i install access into the second machine too?
    thanks
    sandro

    Could it have something to do that on one machine '.' is interpreted as a decimal point, but on the other machine it is interpreted as the , you use in e.g. 1,000 (=1000).
    I would check that both macines use the same Regional Settings (in the control panel).
    Do you use any of the java.text.xxxFormat classes?

  • "0" doesn't display before comma in float numbers...

    Hi fellow APEX users,
    Have you ever experienced this issue with float numbers in your APEX forms?
    When I type float numbers between -1 and 1 in forms (e.g. 0,7 or -0,2), and after having submitted the form then reloaded it for editing, "0" doesn't display before the comma.
    For example I got:
    *,7* instead of *0,7*
    -,2 instead of -0,2
    etc.
    If I look in SQL Workshop, I see the same (no "0") but I'm pretty sure that the value is properly recorded in the database.
    The thing is that it's not very nice for the end users, as they can think the value is wrong.
    Does anybody have a solution to display proper float numbers with "0" in the forms?
    For info I use the NUMBER type.
    Any help much appreciated!
    Thanks,
    Romain.
    Edited by: romain.apex on Feb 5, 2012 8:30 PM

    Hi Peter!
    Of what type is your item? Display as text or do you use the item value for further computations.
    If it is only for means of displaying the correctly formatted number, I'd change the item source to a query and would equip the desired column with a to_char function like:
    select to_char(str_be_main, 'fm999G999G990D00') from yourtable where ...You could also use a post calculation computation and enforce the format there:
    to_char(:P2027_YOUR_ITEM,'fm999G999G990D00')Maybe this helps!
    Brgds,
    Seb
    Edited by: skahlert on 11.02.2011 07:53

  • 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

  • Display float numbers in APEX report

    Hello,
      I have an  interactive report and simple report based on a table with float numbers. Problem is, float numbers with value between 0 and 1 are shown ".1" not "0.1"
    For example, for values 0.1, 1 and 12.1 I get:
    .1
    1
    12.1
      If I add format mask FM999999999999990D99999 to this field, I fix ".1" value, but value "1" becomes "1." which is bad:
    1
    0.1
    1.
    12.1
    What I would like to see in a report is:
    0.1
    1
    12.1
    How could I do it?
    I wrote function which makes needed result as a varchar2 value. Data in reports shows fine, but then problem with sorting arised - data is being sorted as text, not as number, for example:
    1.1
    11.2
    7
    Any ideas?
    Thank you

    So finally seems everything is working now. I even do not need additional column with required format.  And i guess it will work on all apex 4 versions
    Have float column (named lets say ir_float ) and do not use any format on it, leave it as it is. Then the only bad case is ".1" instead of "0.1"
    Add dynamic action after refresh, specify region (which must have template, even for IR) and add java script action:
    For interactive reports:
    $('.apexir_WORKSHEET_DATA td[headers="ir_float"]').each(function(){   
        if(jQuery(this).text().substr(0,1) == '.'){
             jQuery(this).prepend('0')
    For classic reports:
    $('#R930945330216409887 td[headers="ir_float"]').each(function(){   
        if(jQuery(this).text().substr(0,1) == '.'){
             jQuery(this).prepend('0')
    BIG thanks for your ideas fac586
    Giedrius

  • Spawning pages with page numbers "page 1 of 1"

    I'm using a calculation script to define "page 1 of 2" in a form. The script is as follows.
    //set the page number to number 1
    this.pageNum = 1;
    //use the page of page format
    event.value = "Page " + (event.target.page+1)+" of " + (this.numPages);
    This works fine, however, when I start spawning pages the numbers get mixed up. For example, if I spawn one page, the "page 1 of 1" on page one changes to "page 1 of 2." On page two, it reads "page 0 of two." I just can't seem to get the "page n of n" to work with spawned pages. Any suggestions would help.
    Thank you

    For each page's field number page you need to go to that page in the calculation script. You could also turn off calculations during the spawning of the pages and then turn it back on and recalculate the form.
    // code to spawn template;
    // turn off automatic calculation;
    this.calculate = false;
    var t = this.templates;
    var T = t[0];
    T.spawn(this.numPages, true);
    // trun automatic calculation back on;
    this.calculate = true;
    // force recalculation;
    this.calculateNow();
    // end spawn template;
    // custom calculation script for numbering pages;
    var cField = event.target.name;
    var aField = cField.split(".");
    if(aField.length > 1) {
    // get page number for form field from field name & go to that page;
    this.pageNum = aField[0].substr(1,1);
    // update field's value;
    event.value = (this.pageNum + 1) + " of " + this.numPages;
    // update field's default value;
    event.defaultValue = event.value;
    // end custom calculation for numbering pages;

  • Calculating with attributes occurs problems in aggregation ...?

    Hi Gurus, I have a question concerning the calculation with attributes:
    I have created variables (as replacement path) based on a product attribute. The variables (with the attribute value) do work properly and I get the right numbers in the lowest hierarchy level.
    Problem: within my hierarchy structure the query does not aggregate but reports errors ("X") in the upper hierarchy levels. How can I solve this problem?
    Thank you for answering.
    Greetings from T. Duong

    Hi, I already have tried this but it didn't lead to the required result.
    Still thank you for answering. I have seen in SAP Help that the options in extend properties might solve similar problems ... still mine cannot be solved by this. The problem is not the attribute value itself, as I found out.
    I have another thread here, where I defined my problem that occurs due to a formula collision between a structure and a hierarchy.
    Thank you.
    Best regards
    T. Duong

  • Working with Large Numbers

    Hi there,
    I am currently doing a school assignment and not looking for answers but just a little guidance.
    I am working with large numbers and the modulo operator.
    I might have some numbers such as :
    int n = 221;
    int e = 5;
    int d = 77;
    int message = 84;
    int en = (int) (Math.pow(message, e) % n);
    int dn = (int) (Math.pow(en, d) % n);Would there be a better way to do this kind of calculation. The dn value should come out the same as message. But I always get something different and I think I might be losing something in the fact that an int can only hold smaller values.

    EJP wrote:
    It might make sense in some contexts to have a positive and negative infinity.
    Yes, perhaps that's a better name. Guess I was harking back to old COBOL days :-).(*)
    But the reason these things exist in FP is because the hardware can actually deliver them. That rationale doesn't apply to BIgInteger.Actually, it does. All I'm talking about is a value that compares higher or lower than any other. That could be done either by a special internal sign value (my slight preference) or by simply adding code to compareTo(), equals() and hashCode() methods that takes the two constants into account (as they already do with ZERO and ONE).
    Don't worry, I'm not holding my breath; but I have come across a few situations in which values like that would have been useful.
    Winston
    Edited by: YoungWinston on Mar 22, 2011 9:07 AM
    (*) Actually, '&plusmn;infinity' tends to suggest a valid arithmetic value, and I wasn't thinking of changing existing BigInteger/BigDecimal maths (except perhaps to throw an exception if either value is involved).

  • How to paste calculated values from Numbers?

    When I copy calculated values from Numbers and paste into a table in Pages, I get an image like the one below.  Non calculated values paste fine.
    To get around this issue, I paste the calculated values into TextWrangler, then copy from there and paste into Pages.  Is there a way to go directly from Numbers to Pages with calculated values?

    Hi 4th Space,
    I you are pasting into a table in Pages, follow Jeffs instructions.
    I you are not pasting into a table, this works. Copy the cells in Numbers. Go to your Pages document and under the Edit Menu > Paste and Match Style. It works like Paste Values.
    Ian.

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

  • I have 1 apple id, 2 5S iPhones with separates numbers and both ring when I get a call on one of the numbers. How do I switch that of ?

    I have 1 Apple ID, 2 5S iPhones (1 private/1 work) with separates numbers and both phones ring when I get a call on one of the numbers. How do I switch that of ?

    I realize that my wife could make her own iTunes account; however, she's been using mine for about 2 years now and this hasn't been an issue.  I guess with the Family Sharing she can have access to all of our music and apps now with her own account. 
    I'll have to see if unchecking our emails resolves this issue.

  • I bought a new iphone and as i was setting my apple ID account and i signed in to my account and confirmed two useres with diffrent numbers that were signed to the same apple ID and it messed up my i messege and face time. how do i fix that ?

    i bought a new iphone and as i was setting my apple ID account and i signed in to my account and confirmed two useres with diffrent numbers that were signed to the same apple ID and it messed up my i messege and face time. how do i fix that or delete one user ?

    Hello sapiii96,
    Thanks for using Apple Support Communities.
    For more information on this, take a look at:
    iOS: Troubleshooting FaceTime and iMessage activation
    http://support.apple.com/kb/ts4268
    To sign out of your Apple ID
    Go to Settings > FaceTime, tap your Apple ID, and select Sign Out.
    Go to Settings > Messages > Send & Receive, tap your Apple ID, and select Sign Out.
    Best of luck,
    Mario

Maybe you are looking for

  • Remote Connecting to a PC from my Mac

    Hi, I am wondering how I can essentially "screen share" with my friend using a pc. By this I mean they share their screen. I've been looking on the internet for answers and I have found multiple hits for connecting from PC to Mac but not the other wa

  • Voicemail is messed up!

    i returned my last iphone and got a new one. i rerecorded my voicemail greeting and set it as my voicemail greeting thing. but everytime someone calls me and it goes to my voicemail it doesnt give them the option to leave a voicemail. please help.

  • NAC Appliance and LDAP Lookup

    Hello, I have two CAM in HA and two CAS in HA. I configure the LDAP Lookup for create rule to role allocation. In this configuration are only one windows server to make find the user properties. There are one problem when this Windows servers is down

  • Why doesn't my iTunes on Windows 7 have any synchronizing options for my new ipad.

    this is all I have got from my Itunes.  It does recognise that I have connect my ipad to the itunes, but it does not give me any synchronising options as it is supposed to have such as videos, musics. contracts and so on. Can some body helo me please

  • Creating an single ISO for Windows PE 5.1 32/64 bit

    Hi With MDT 2013 and Windows ADK, how do I create a single ISO that, at startup, allows to choose whether to run Windows PE 5.1 32 bit or 64 bit? Thanks Bye Balubeto