I would like some help with my code. I'm doing a method to convert binary numbers to decimals. This is my code:
public double decimal(double number){
String num=(number+"");
char charac;
double n;
double cont=0;
double exp;
double res=0;
for(int i=num.length()-1;i>=0;i--){
charac=num.charAt(i);//obtains digits 1 by 1 and converts to char
n=(Character)charac;//converts the digit into a number (double)
exp=Math.pow(2, cont);//makes the exponential function to multiply to n
n=n*exp;//multiplies exponential with the digit
res+=n;//adds digit to accumulator
cont++;
}
return res;
}
the problem i'm having is that the numbers get all messed up for whatever reason, like n being assigned 48 in the first loop of the for cycle.
I tried using n as an Int instead and it seemed to be working well but at the second loop of the for cycle it was assigned -2 somehow and that ruined the addition.
Change
n=(Character)charac;
to use Character.digit(char, int) otherwise you get the ascii value (not the digit value)
n=Character.digit(charac, 10);
By assigning char to double, it is infact passing on the ASCII value of that digit e.g. 48 is returned for char 0.
I think this answer from How to convert binary string value to decimal will help you:
String c = "110010"; // as binary
int decimalValue = Integer.parseInt(c, 2);
System.out.println(decimalValue);
result: 50
Related
I am trying to figure out how to convert hex into a string and integer so I can manipulate an RGB light on my arduino micro-controller through it's serialport. I found a good example on the java website, but I'm having a difficult time understanding some of the methods and I am getting hung up. I could easily just copy-paste this code and have it work but I want to fully understand it. I will add comments to my understandings and hopefully someone can provide some feedback.
public class HexToDecimalExample3{
public static int getDecimal(String hex){ //this is the function which we will call later and they are declaring string hex here. Can we declare string hex inside the scope..?
String digits = "0123456789ABCDEF"; //declaring string "digits" with all possible inputs in linear order for later indexing
hex = hex.toUpperCase(); //converting string to uppercase, just "in case"
int val = 0; //declaring int val. I don't get this part.
for (int i = 0; i < hex.length(); i++) //hex.length is how long the string is I think, so we don't finish the loop until all letters in string is done. pls validate this
{
char c = hex.charAt(i); //char is completely new to me. Are we taking the characters from the string 'hex' and making an indexed array of a sort? It seems similar to indexOf but non-linear? help me understand this..
int d = digits.indexOf(c); //indexing linearly where 0=1 and A=11 and storing to an integer variable
val = 16*val + d; //How do we multiply 16(bits) by val=0 to get a converted value? I do not get this..
}
return val;
}
public static void main(String args[]){
System.out.println("Decimal of a is: "+getDecimal("a")); //printing the conversions out.
System.out.println("Decimal of f is: "+getDecimal("f"));
System.out.println("Decimal of 121 is: "+getDecimal("121"));
}}
To summerize the comments, it's primarily the char c = hex.charAt(i); AND the val = 16*val + d; parts I don't understand.
Ok, let's go line for line
public static int getDecimal(String hex)
hex is the parameter, it needs to be declared there, so you can pass a String when you call the function.
String digits = "0123456789ABCDEF";
Yes, this declares a string with all characters which can occur in a hexadecimal number.
hex = hex.toUpperCase();
It converts the letters in the hex-String to upper case, so that it is consistent, i.e. you always have F and never f, no matter which is being input.
int val = 0;
This is the variable where the corresponding decimal value will later be in. We will do our calculations with this variable.
for (int i = 0; i < hex.length(); i++)
hex.length() is the number of characters in the hex-String provided. We execute the code inside this for loop once per character.
char c = hex.charAt(i);
Yes, char represents a single character. We retrieve the character from the hex-String at index i, so in the first iteration it is the first character, in the second iteration the second character and so on.
int d = digits.indexOf(c);
We look which index the character has in the digit-String. In that way we determine the decimal representation of this specific digit. Like 0-9 stay 0-9 and F becomes a 15.
val = 16*val + d;
Let's think about what we have to do. We have the decimal value of the digit. But in hexadecimal we have this digit at a specific position with which it gets multiplied. Like the '1' in '100' is actually not a 1, but 100 * 1 because it is at this position.
10 in hexadecimal is 16 in decimal, because we have 1 * 16. Now the approach here is a little bit complicated. val is not uninitialized. val is 0 at the beginning and then contains the cumulated values from the previous iterations. Since the first character in the String is the highest position we don't know directly with what we have to multiply, because we don't know how many digits the number has (actually we do, but this approach doesn't use this). So we just add the digit value to it. In the consecutive iterations it will get multiplied by 16 to scale it up to the corresponding digit base value. Let me show you an example:
Take 25F as hex number. Now the first iteration takes the 2 and converts it to a 2 and adds it to val. The 16 * val resolves to 0 so is not effective in the first time.
The next iteration multiplies the 2 with 16 and takes the 5 (converted to 5) and adds it to val. So now we have (I split it mathematically so you understand it):
2 * 16 + 5
Next we get the F which is decimal 15. We multiply val by 16 and add the 15.
We get 2 * 256 + 5 * 16 + 16 (* 1), which is actually how you calculate the decimal value of this hex value mathematically.
Another possibility to compute val is:
val += Math.pow(16, hex.length() - i - 1) * d;
For example, I am having 12.12 float value I want it to become 1212 an integer value
If I am having 156.2345 I want it to be 1562345.
I have searched a lot but found only rounding and casting to int but no answer for my question.
Moreover, if we have 12.12000 then also I should be getting 1212 only but not 1212000.
The problem is I will be reading double or float from stdinput and I have to convert that to appropriate int as per above rules
Tried Float.intValue() among others, but that gives 12 only
Use following:
floatValue.toString().replaceAll("[0]*$", "").replace(".", "");
First replace will remove all trailing 0s from the float value while second replace will remove the dot.
I am not sure it's a good idea to do this but you can do
double d = 12.12;
long n = Long.parseLong(BigDecimal.valueOf(d).toString().replaceAll("[.,]", ""));
This will drop any decimal places. You can use float and int instead.
If you want 1.0 to be 1 instead of 10, and 10.0 to be 1 instead of 10or 100 you can add
.replaceAll("[0]*$", "")
Tried Float.intValue() among others, But that gives 12 only
As it should. intValue returns the value as an int rounded down.
Here's an alternative approach that multiplies the number by 10 until the remainder division by 1 yields 0:
static long toLong(double d) {
if (d % 1 != 0) {
return toLong(d * 10);
}
return (long) d;
}
Integer.parseInt(Float.toString(value).replaceAll(Pattern.quote("."), ""));
The shortest and safe code.
replaceAll() takes regex as argument, so you must use Pattern.quote();
Integer.parseInt(): Parses an Integer from String. (ex: "123" -> (int)123)
Float.toString(): Converts a Float to String. (ex: 12.34 -> "1234")
replaceAll(String regex, String change_to): Replace all 'regex' to change_to.
I use apach commons library(org.apache.commons.lang.math.Fraction).
Now I compare int and Fraction object like this:
private static final int MAX_VALID_RATIO = 3;
....
fraction.compareTo(Fraction.getFraction(MAX_VALID_RATIO, 1))
It looks not nice.
Fraction.getFraction(MAX_VALID_RATIO) has only double builder.
Can you advise nicer way?
You can just retrieve the intValue() of the Fraction and compare with your value:
Gets the fraction as an int. This returns the whole number part of the fraction.
This method will return the value of the fraction truncated of the decimals. For example, the fraction 10 / 3 will have an intValue() of 3.
boolean greater = fraction.intValue() >= MAX_VALID_RATIO
Comparing an integer to a fraction can be done best in 2 steps:
Get fraction.intValue and compare to your int. If your int is strictly greater or smaller than the fraction's intValue() you can stop here.
Otherwise get the fraction's deliminator and numerator and do: deliminator % numerator. If this results in 0, they are equal, otherwise the fraction is bigger.
I am wanting to store an integer named Amount, I want it to be stored in pence so if the user entered 11.45 it would be stored as 1145. What is the best way to remove the decimal point? Should I be using decimalFormatting in Java?
Edit:
It is entered in string format, was going to covert it to an int. I will give one of your solutions ago and let you know if it works but not sure which one would be the best.. Thanks everyone.
times it by 100 and cast as int. Use decimal formatting is double / float are too inaccurate which they may be for money
If the user input is in the form of a string (and the format has been verified), then you can strip out the decimal point and interpret the result as an integer (or leave it as a string without the decimal point).
String input = "11.45";
String stripped = input.replace(".", ""); // becomes "1145"
int value = Integer.parseInt(stripped);
If it's a float already, then just multiply by 100 and cast, as #user1281385 suggests.
What about convert to float, multiply by 100 and then convert to int?
String pound = "10.45"; // user-entered string
int pence = (int)Math.round(Float.parseFloat(pound) * 100);
This might be also useful: Best way to parseDouble with comma as decimal separator?
Tested and works. Even if the user enters a number without a decimal, it will keep it as such.
double x = 11.45; // number inputted
String s = String.valueOf(x); // String value of the number inputted
int index = s.indexOf("."); // find where the decimal is located
int amount = (int)x; // intialize it to be the number inputted, in case its an int
if (amount != x) // if the number inputted isn't an int (contains decimal)
// multiply it by 10 ^ (the number of digits after the decimal place)
amount = (int)(x * Math.pow(10,(s.length() - 1 - index)));
System.out.print(amount); // output is 1145
// if x was 11.4500, the output is 1145 as well
// if x was 114500, the output is 114500
I'm trying to declare a method for my program that takes only a 5 digit integer and for each digit of the integer, reads a value from the program and prints it out. I understand this isn't very clear but im having trouble relaying what I mean. I understand it will be some sort of for loop to read each digit of the integer individually until something reaches 5. Something like the charAt() string method but works for digits.
Read up on "modulo". It is a primitive operation, available via the symbol % in Java.
For division, it is the remainder. So
System.out.println("Last digit: "+(12345 % 10));
will print 5. Figure out yourself how to get the other digits.
As an exercise, figure out how to print binary digits.
You can divide and take modulo.
while(n > 0) {
System.out.println("Digit " + (n % 10));
n /= 10;
}
This works fine if you are using any base: all you need to do is substitute 10 for the base (dividing by the base means shifting everything left, and taking the modulo means getting the last digit).
You can very easily convert your integer to a string and use charAt()
String parseableString = Integer.toString(yourInt);
for (int i = 0; i < parseableString.length(); i++){
System.out.println(parseableString.charAt(i));
}