Search code examples
javaparsingnumber-manipulation

How to break a number into different parts in Java?


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


Solution

  • 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.