-2

Is there a way to force a number to be placed behind the decimal mark of a number?

Say I have a number = 2, and another number = 23. Is there a way for me to force 23 into 0.23, so that when I add the numbers I end up with 2.23? And is there a way to do this when the number of digits in the second number, in this case 23, are unknown?

EDIT: I realize this was badly written. I am currently working on a program that converts from imperial units to metric units. Part of the code looks like this:

double feet = nextDouble();
double inches = nextDouble();
double heightInMeters = (feet + (inches/10)) / 3.2808;

The problem with this code is that I anticipate that the user only enters a value <0, 9> for feet. Is there a way to force the input for inches to something like 0.x where x = inches so that it doesn't matter if the number is greater than 9?

Would be lovely if it was possible without using toString() and parseInt().

3 Answers3

2

You can get the number of digits in an integer, i, using:

1 + Math.floor(Math.log10(i))

(not ceil(log10(i)), since that calculates that 1 has zero digits)

You then need to divide i by 10 to the power of that number:

i / Math.pow(10, 1 + Math.floor(Math.log10(i)))

e.g.

23 / Math.pow(10, 1 + Math.floor(Math.log10(23))) == 0.23

Ideone demo


Alternatively, if you think those floating point operations log and pow are too expensive, you can determine the number of digits with a loop:

int d = 1;
while (d < i) d *= 10;

then

System.out.println(i / (double) d);

(noting that you need to cast at least one of the numerator or denominator to a floating point type, otherwise it will use integer division).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Try parsing to double like this, from a string:

Option 1

try
{
    int n = 2;
    int decimal = 23;
    String full = Integer.toString(n) + '.' + Integer.toString(decimal);
    double val = Double.parseDouble(full);
} catch (Exception e) //Or whatever exception 
{
    //Code
} 

Option 2

Of course, there are simpler methods, like this:

try
{
    int n = 2; 
    int decimal = 23;
    double val = Double.parseDouble(n + "." + decimal);
} catch (Exception e) //Or whatever exception 
{
    //Code
} 

I personally would recommend the solution directly above, since it is the simplest, and requires the least code.


Live Example for Second Option
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

Simple implementation using Strings:

public class Mainclass {
    public static void main(String[] args) {
        Integer num = 1546;
        Integer num2 = 2;

        String s = num.toString();
        s = "0." + s;
        Double d = Double.parseDouble(s);
        System.out.println(num2+d ); // 2.1546
    }
}
chenchuk
  • 5,324
  • 4
  • 34
  • 41