Hi,
I'm looking to do the following : let's say I have a number like 125.625 => I would like to be able to tell my program that is 1 * 100 + 2 * 10 + 5 * 1 + 0.625. How could I do that please ?
thanks
Hi,
I'm looking to do the following : let's say I have a number like 125.625 => I would like to be able to tell my program that is 1 * 100 + 2 * 10 + 5 * 1 + 0.625. How could I do that please ?
thanks
If you have your number as an integer, you could do something like this:
value := 125.625
fractional part := value % 1
value := floor(value)
exponent = 1
listofvaluepairs = array()
while(value > 0)
{
tmp_part := value % 10
listofvaluepairs.add(value, exponent)
exponent = exponent * 10
value = floor(value / 10)
}
The above psuedocode will fill the listofvaluepairs with pairs of the digit and the number to multiply by. So you'd get this:
{{1,100}, {2,10}, {5,1}}
And the fractional part has that last piece you wanted.
For reference, the floor() function will give the number without the fractional part, so floor(1.6) gives 1. The % (modulo) operator will more or less give the remainder after division. So 7%2 = 1.
What I do in the above example (which is very much not java code), is get one digit at a time from the value.
So I start with 125:
125 % 10 = 5
Then:
floor(125 / 10) = floor(12.5) = 12
Then I repeat to get 2 and 1. At the same time I'm saving 1, 10, and 100 using the exponent variable.
You can get each digit by using the modulo or %
operator in a loop for the integer values (i.e.: int ones = myVal % 10
), and to get the fractional value do float fraction = val - (int)val;
double num = 125.625;
System.out.print(num - (int)num);
num = (int) num;
for (int i=10; num!=0; i*=10) {
System.out.print(" + " + i/10 + " * " + (num % i)/i*10);
num -= num % i;
}
Will print:
0.625 + 1 * 5.0 + 10 * 2.0 + 100 * 1.0
Of course you can change the code to add stuff to a data structure.