Hi, quick question
I have 2 values x and y. How can I create a float (z = x.y) where the '.' is the decimal point.
Printable View
Hi, quick question
I have 2 values x and y. How can I create a float (z = x.y) where the '.' is the decimal point.
You need to convert it to a float object first, or you could parseFloat which is actually doing the same thing as the first line of code.
Code:int one = 1;
int two = 2;
float result = Float.valueOf(one + "." + two).floatValue();
//or float result = Float.parseFloat(one + "." + two);
System.out.println("The float value is: " + result);
Yeah right, do you know the overhead if I wanted to go with the parse. I think I'll keep looking :)
Well if you don't want the overhead of creating the Float object, then you could use some math.
Code:int one = 22;
int two = 8;
float f1 = (float)(two / 10.0);
float f2 = one + f1;
System.out.println("Final: " + f2);
Ok that would work if the 2nd number is a single digit. How about 88. I think a bit shifting operation might be better
I always find that bit shifting adds unnecessary complexity to a program so I try to avoid it when not completely necessary. You may still want to use it, but with some more math, you can accommodate any length of decimal.
Code:int one = 22;
int two = 8123;
double base10 = Math.log(10);
//find out of the number is in the 10's, hundreds or thousands, etc
//this result will be 1 less, but that is perfect for what we're doing here
int decLength = (int) (Math.log(two) / base10);
//find the proper divisor for the below statement
float divisor = (float)Math.pow(10,(decLength));
float f1 = (float)(two / divisor);
System.out.println(f1);
float f2 = one + f1;
System.out.println("Final: " + (f2));
lol thanks for the help but your program output is:which has nothing to do with the input values. The output should be 22.8123 not 8.123Quote:
8.123
Final: 30.123001
Whoops sorry, that was because I made an error in my thinking.
Change
ToCode:int decLength = (int) (Math.log(two) / base10);
Code:int decLength = 1 + (int) (Math.log(two) / base10);
Thanks I'm sorry I can't rep you because I have to spread for some people