Click to See Complete Forum and Search --> : [RESOLVED] Convert 2 integers into a float
ComputerJy
Jan 6th, 2010, 04:03 AM
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.
kfcSmitty
Jan 7th, 2010, 08:45 PM
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.
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);
ComputerJy
Jan 8th, 2010, 03:44 AM
Yeah right, do you know the overhead if I wanted to go with the parse. I think I'll keep looking :)
kfcSmitty
Jan 8th, 2010, 08:14 AM
Well if you don't want the overhead of creating the Float object, then you could use some math.
int one = 22;
int two = 8;
float f1 = (float)(two / 10.0);
float f2 = one + f1;
System.out.println("Final: " + f2);
ComputerJy
Jan 8th, 2010, 08:19 AM
Ok that would work if the 2nd number is a single digit. How about 88. I think a bit shifting operation might be better
kfcSmitty
Jan 8th, 2010, 08:56 AM
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.
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));
ComputerJy
Jan 8th, 2010, 09:17 AM
lol thanks for the help but your program output is:8.123
Final: 30.123001which has nothing to do with the input values. The output should be 22.8123 not 8.123
kfcSmitty
Jan 8th, 2010, 09:31 AM
Whoops sorry, that was because I made an error in my thinking.
Change
int decLength = (int) (Math.log(two) / base10);
To
int decLength = 1 + (int) (Math.log(two) / base10);
ComputerJy
Jan 8th, 2010, 04:27 PM
Thanks I'm sorry I can't rep you because I have to spread for some people
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.