Binary number to decimal

Hi
I realy need help with my java program because something is built wrong and is does not working properly.
I attached my program:
import java.util.Scanner;
import java.lang.*;
public class BinaryToDecimal {
public static void main (String [] args) {
String a;
int b;
double sum;
Scanner reader=new Scanner(System.in);
System.out.println("Enter a binary String: \t");
String binary=reader.nextLine();
sum = 0;
for (int i = 0; i < binary.length(); i++) {
a = Character.toString(binary.charAt(binary.length() - i -1));
sum = sum + Integer.parseInt(a) * Math.pow(2, i);
System.out.println(sum);
If somebody can check this because the output is wrong

1) When you post code, use the CODE button or [code and [/code] tags.
2) Define "not working."
3) Do you have to write this method yourself? If not, look at the docs for java.lang.Integer.
4) Print out sum inside the loop so you can see what's happening each time. Also print out other variables, the results of intermediate calculations, etc., so you can see which code is being executed, how many times, and what it's doing.

Similar Messages

  • About binary number and decimal number?

    how to use a class to convert a decimal number from a binary number?Thank you

    You've already asked the same kind of thing before (http://forum.java.sun.com/thread.jsp?forum=31&thread=325249), and fsato4 answered. Here is the same thing, but decimal to binary.
    public class ToBinary {
         public static void main(String[] args) {
              int n = 12; 
              System.out.println(Integer.toString(n)); 
              System.out.println(Integer.toBinaryString(n));

  • Binary numbers to decimal numbers

    Hello, Im writing a program that changes binary numbers to decimal numbers. I seem to be having a probelm calculating the last number in the binary code and adding it to the total. Also, when I use large binary numbers the output isnt anywhere near correct. help? please? thank you

    public class binarynumbers
    public static void main (String [] args)
    int decimal=0;
    Scanner scan= new Scanner(System.in);
    System.out.print("enter binary number> ");
    String bin=scan.next();
    int zero=0;
    int one=1;
    int length=bin.length();
    int newlen=length-1;
    while (newlen>=0)
         String number = bin.substring( zero , one );
         int number1=Integer.parseInt(number);
         int squareRoot=Math.pow(2,newlen);
         decimal+=(squareRoot*number1);
         newlen--;
         zero++;
         one++;
    System.out.println("The decimal number translation is " + decimal);
    i did that but the math part isnt working and im getting a message like this
    binarynumbers.java:26: possible loss of precision
    found : double
    required: int
         int squareRoot=Math.pow(2,newlen);
    ^
    1 error

  • Round a double value to a specific number of decimal places?

    Hello,
    Is there standard java function which will round a double value to a specified number of decimal places? Something like:
    double d = 4.34523;
    d = round(d, 2);
    where d is finally assigned the value of 4.34?
    Thanks!
    -exits

    No, because doubles hold values in binary (as do all values in a computer, of course, but there's no additional stuff to indicate decimal values).
    If you want values with specific rounding rules in decimal, use java.math.BigDecimal.
    If you just want to format the number with a specified number of decimal digits, use java.text.DecimalNumber.

  • Can not change the number of decimal places in the normalization of result

    dear all
        i want to see the proportion of some data, for example, the income of May is 300, and the total income is 1000, i need to display it like 33.33% . so i set the
    Calculate single values as normalization of result, and then it display 33.333%, i like to display only two number of decimal places, so i set the number of decimal places as 0.00, but i doesn't work, it still display three decimal numbers.
        maybe you say i can use the percentage function like %CT %GT %RT, but i need to allow external access to my query, so the i can not use those functions.
        can somebody helps me ? your advice is appreciated.

    hi,thanks for your advice, but that doesn't suit for my problem.
    before i set the normalization of result, i can change the decimal values. After that i cann't.
    In your thread, someone proposes use the T-code OY04. but this wouldn't help. As i change to other key figure, such as user quantity, when i set normalization of result, it still display 3 decimal values.
    i think the point maybe lie in the normalization of result. please advise... thanks...

  • How to get the number of decimal places configured for a site column

    Hi,
    I have a column 'SampleNumCol' of type Number, the number of decimal places to be displayed is configured as 2.
    The column conatins a value, but when retrieved programatically is displayed as 5.00000000  instead of 5.00.
    I am retrieving this column using listitem.Properties[field.InternalName].
    I need to trim the decimals based on  number of decimal places configured for the site column.
    How to get the number of decimal places configured for a site column?
    Thanks in advance,
    dhijit

    Get the field as SPFieldNumber and then check DisplayFormat which returns
    SPNumberFormatTypes
    SPFieldNumber numberField = list.Fields.GetFieldByInternalName("YourNumberFieldName") as SPFieldNumber;
    SPNumberFormatTypes numFormatType = numberField.DisplayFormat;

  • Change number of decimal in general settings after working .

    Hi,
    My customer was upgarded to sap2007 and changed the number of decimal in the "Amount" field to 4 ( it used to be 2)
    now after working a while he needs to change it back.
    Do you know what are the consequences of updating this field using an update query?
    thanks.

    Disaster - first SAP does not permit direct updates to the database it is a violation of agreement with both customers and partners.
    Second - even if you were to update the field your reports, fiancials, etc would never match due to rounding and display differences.
    I am guessing that the client does not like the 4 decimals on the forms and if this is the case they could be changed to display a rounded field by creating a new field, linking to the old field and using a formulae such as round(field_123,2). You would then die the old field.
    It is for this reason that SAP clearly warns you that setup of decimals are critical and cannot be changed after transactions are entered.

  • Yielding the desired number of decimal places using the AVG function in t-sql

    Hello again.  Confused retired hobby coder having trouble setting up a scalar-valued function to return the desired number of decimal places from a AVG query.
    Whenever I run the following script I get the number of decimals I desire:
    Using the above I created a scalar-valued function as follows:
    Running this function as: SELECT [dbo].[TestHCIPartial] (1,3)  my return is -7.
    Can you help me with the function causing it to yield the answer to 6 decimal places?
    Thanks and regards, Minuend.

    You've not specified precision and scale in UDF return type. So you're leaving it to server to interpret it based on default settings
    If you want exactly up to four decimal places tweak udf as below
    ALTER FUNCTION..
    RETURNS decimal(20,4)
    AS
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Altering number of decimal places of formatted number

    Using http://java.sun.com/docs/books/tutorial/i18n/format/numberFormat.html I have worked out how to format a number, almost. When I follow the example in this tutorial that shows how format a double, it always rounds it to 3 decimal places. How do I alter the number of decimal places that this formatting procedure outputs? I used the US as the locale and English as the language. I am assuming that if these parameters are chosen, 3 decimal places is the output. Is this assumption correct?

    Look at the next chapter :)
    http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html

  • Bex: overall Result: number of decimal places

    Good day
    How to I change the number of decimal places for the "Overall result" in a query?
    Your assistance is appreciated.
    Cj Faurie

    Thanks for your response.
    The number format in properties for the KF (formula created in query) has been set to '0' decimal places. I also use the "Average of all values <>0" in the calculate results for the KF. If you use "Summation" then the decimal will apply, but not with the "Average .....".
    My "0CALMONTH" is in rows and results is based on this (set to 'never') as I want the Overall Result to display first as my chart is based on the OResult and not the individual figures.
    "This is the layout of my report"
    Territory     Overall Result    2007/02     2007/03    2007/03
    Boland       205.8333           21             242          355
    The "overall result' should display as '206'. Why does the 'decimal place' not apply to "Average of all v...."?
    Thanks
    Cj

  • BEx Analyzer displays wrong number of decimal places after implementing BW patch

    Hey folks,
    we patched our BW 7.31 from PL10 to PL15 last weekend and now we got some issue with the number of decimal places shown in BEx Analyzer 7.x.
    One example for KF X
    Settings Info Object X
    Decimal Places:                         Not defined
    RSRT - Display X
    Shows 3 decimal places
    Query Designer Settings using KF X
    Number of Descimal Places:     0  [Use Default Settings: NO]
    BEx Analyzer Properties for KF X
    Decimal Places:                         0
    Resulting in BEx Analyzer workbook shows 3 decimal places instead of 0!
    Anyone with an good idea about that?
    Thanks,
    Andreas

    Hi Andreas,
    Have you used the list calulation like "Calculate Result As Average" or "Calculate Single Values as normalization of result" in the relevant key figures?
    For "Calculate Single Values as normalization of result",iIt is the known design that it is always displayed with three decimal places for normalized values, and the setting in Query Designer for
    decimal place doesn't take effect.
    For "Calculate Result As Average", the following note maybe relevant.
    2096911 - Decimal places in query result is wrong, if average is used and display precision is set to less than 3, it will always show 3 decimal places.
    Another clue is to check if the key figure is a Quantity type with unit, and what's defined in table
    T006 field ANDEC for this unit.
    Hope this helpful.
    Regards,
    Ceciclia

  • Determine Number of Decimal Place using BigDecimal

    I was interested to have the following getNumberOfDecimalPlace function :
    System.out.println("0 = " + Utils.getNumberOfDecimalPlace(0)); // 0
    System.out.println("1.0 = " + Utils.getNumberOfDecimalPlace(1.0)); // 0
    System.out.println("1.01 = " + Utils.getNumberOfDecimalPlace(1.01)); // 2
    System.out.println("1.012 = " + Utils.getNumberOfDecimalPlace(1.012)); // 3
    System.out.println("0.01 = " + Utils.getNumberOfDecimalPlace(0.01)); // 2
    System.out.println("0.012 = " + Utils.getNumberOfDecimalPlace(0.012)); // 3
    I use the following code
        public static int getNumberOfDecimalPlace(double value) {
            final BigDecimal bigDecimal = new BigDecimal("" + value);
            final String s = bigDecimal.toPlainString();
            System.out.println(s);
            final int index = s.indexOf('.');
            if (index < 0) {
                return 0;
            return s.length() - 1 - index;
        }However, for case 0, 1.0, it doesn't work well. I expect, "0" as result. But they turned out to be "0.0" and "1.0". This will return "1" as result.
    0.0
    0 = 1
    1.0
    1.0 = 1
    1.01
    1.01 = 2
    1.012
    1.012 = 3
    0.01
    0.01 = 2
    0.012
    0.012 = 3
    Any solution?

    Please [don't cross-post!|http://stackoverflow.com/questions/2296110/determine-number-of-decimal-place-using-bigdecimal], it's considered rude. If you must do it, then at least link each post so that people can find out which answers you've already got in order to avoid duplicate work on our part.
    Please read [_How To Ask Questions The Smart Way_|http://www.catb.org/~esr/faqs/smart-questions.html].

  • Count number of decimal

    Hi all,
    I have the table
    List
    flag_circ char(1)
    impo number(11,3)
    and I have to update flag_circ, if the number of decimal of the field impo, are 0 or 1
    For example
    Impo value
    123,444 --> no update
    123,44 --> no update
    123,4 --> yes update
    123 --> yes update
    I'm trying those functions like round, mod, trunc, but don't work!
    Some suggestions?
    Thank's form Madrid
    Paolo

    Hi,
    Try this
    UPDATE list
    SET flag_circ = somthing you want
    WHERE INSTR(impo,'.',1,1) = 0
    OR
    LENGTH(SUBSTR(impo,INSTR(impo,'.',1,1)+1,2)) = 1
    My tests:
    SQL> WITH data_Set AS
    2 (
    3 SELECT 1 row_no, 1221.4554 text_col FROM dual
    4 UNION ALL
    5 SELECT 2 row_no, 1221.4554 text_col FROM dual
    6 UNION ALL
    7 SELECT 3 row_no, 1234 text_col FROM dual
    8 UNION ALL
    9 SELECT 4 row_no, 2343.5 text_col FROM dual
    10 )
    11 SELECT row_no FROM data_set
    12 WHERE INSTR(text_col,'.',1,1) = 0
    13 OR
    14 LENGTH(SUBSTR(text_col,INSTR(text_col,'.',1,1)+1,2)) = 1
    15 /
    ROW_NO
    3
    4
    Regards,
    Raj
    www.oraclebrains.com

  • Setting number of decimal points using double

    Is it possible to set the number of decimal points
    e.g.
    double a = 2 * Math.random() - 1;
    If I print this it would show something like 0.2342345434332.
    What I want to do is show 0.234.
    Is this possible?

    here you go, you can run this small program to test the results for yourself...
    import java.text.DecimalFormat;
    public class floatTest{
         public static void main( String args[]){
    DecimalFormat threeDig =  new DecimalFormat("0.000");
          double a = 2 * Math.random() - 1;
          //If I print this it would show something like 0.2342345434332.
          System.out.println("double a >" + a);
    System.out.println("formatted>0.000 >" + threeDig.format(a)     );
         }//end of float
    }//end of floatTEstok?

  • Converting a binary number to a list of integers

    I need to convert a binary number to a list of the values of the bit possitions that make up that number. I.e. 1 = 1; 3=2,1; 7=1,2,4.
    Does anyone know of Java API functions that could accomplish this, I couldn't find any, or a function that can do this?

    This reminds me of my programming homework assignments...
    There are some very efficient ways to do this - but I can't remember them off the top of my head. I can guarantee they will have been posted several hundred times before. This will work:
    class BitMask {
        private byte mask = 1;
        public void printBitFields(int a) {
         System.out.print(a + " =");
         for(i = 0 ; (a & Integer.MAX_VALUE) != 0 ; i++) {
             if((a & mask) == 1)
              System.out.print(" " + ((int) java.lang.Math.pow(2,i)));
             a >>= 1;
         System.out.println();
        public final static void main(String args[]) {
         BitMask bm = new BitMask();
         bm.print(1);
         bm.print(18);
         bm.print(19); // etc...
    }

Maybe you are looking for